﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data;
using System.Transactions;

public partial class Main_ServiceInvoice_CreditNoteEdit : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    string strsql = string.Empty;
    int intRowCounter = 1;
    int OldIDCounter = 1;
   

    #region List Variables for Credit note main table
    List<string> LstCount;
    List<string> LstChkDelete;
    List<string> LstInvoiceParticular;
    List<string> LstServiceTaxRate;
    List<string> LstPECessRate;
    List<string> LstHECessRate;
    List<string> LstService;
    List<string> LstServiceTaxability;
    List<string> LstOriginalAmt;
    List<string> LstPendingAmt;
    List<string> LstAddDescription;
    List<string> LstTotalAmount;
    List<string> LstHiddenTotalAmount;

    #endregion
    #region List Variables for Credit note TDS table
    List<string> LstCountCN;
    List<string> LstChkDeleteCN;
    List<string> LstParticularCN;
    List<string> LstServiceCN;
    List<string> LstTDSAmtCN;
    List<string> LstTDSAmtWithoutSTCN;
    List<string> LstDicountCN;
    List<string> LstDicountAmtCN;
    List<string> LstWriteOffCN;
    List<string> LstWriteOffAmtCN;
    List<string> LstServiceTaxAmtCN;
    List<string> LstPECessAmtCN;
    List<string> LstHECessAmtCN;
    List<string> LstTotalAmtCN;
    #endregion
    #region List Variables for Credit note Sale Return table
    List<string> LstChkDeleteSR;
    List<string> LstCountSR;
    List<string> LstParticularSR;
    List<string> LstServiceSR;
    List<string> LstSaleReturnSR;
    List<string> LstSaleReturnAmtSR;
    List<string> LstTotalAmtSR;
    #endregion
    List<string> LstOldIdCounter;
    List<string> LstHidChildCount;
    List<string> LstHidChildID;
    List<string> LstHidRefID;

    //protected override void OnLoad(EventArgs e)
    //{
    //    base.OnLoad(e);
    //    _Override_AddMoreRow_MainTable();
    //    _Override_tblCreditNote();
    //    _Override_tblTDSSaleReturn();
    //}
    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        _Override_AddMoreRow_MainTable();
        
        _Override_tblCreditNote();
        _Override_tblTDSSaleReturn();
        Override_OLDID();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!Page.IsPostBack)
        {
            //*******Credit Note Main Table
            LstCount = new List<string>();
            ViewState["LstCount"] = LstCount;

            LstInvoiceParticular = new List<string>();
            ViewState["LstInvoiceParticular"] = LstInvoiceParticular;

            LstServiceTaxRate = new List<string>();
            ViewState["LstServiceTaxRate"] = LstServiceTaxRate;

            LstPECessRate = new List<string>();
            ViewState["LstPECessRate"] = LstPECessRate;

            LstHECessRate = new List<string>();
            ViewState["LstHECessRate"] = LstHECessRate;

            LstService = new List<string>();
            ViewState["LstService"] = LstService;

            LstServiceTaxability = new List<string>();
            ViewState["LstServiceTaxability"] = LstServiceTaxability;

            LstOriginalAmt = new List<string>();
            ViewState["LstOriginalAmt"] = LstOriginalAmt;

            LstPendingAmt = new List<string>();
            ViewState["LstPendingAmt"] = LstPendingAmt;

            LstAddDescription = new List<string>();
            ViewState["LstAddDescription"] = LstAddDescription;

            LstTotalAmount = new List<string>();
            ViewState["LstTotalAmount"] = LstTotalAmount;

            LstHiddenTotalAmount = new List<string>();
            ViewState["LstHiddenTotalAmount"] = LstHiddenTotalAmount;
            //**********Credit Note TDS Table
            LstCountCN = new List<string>();
            ViewState["LstCountCN"] = LstCountCN;

            LstParticularCN = new List<string>();
            ViewState["LstParticularCN"] = LstParticularCN;

            LstServiceCN = new List<string>();
            ViewState["LstServiceCN"] = LstServiceCN;

            LstTDSAmtCN = new List<string>();
            ViewState["LstTDSAmtCN"] = LstTDSAmtCN;

            LstTDSAmtWithoutSTCN = new List<string>();
            ViewState["LstTDSAmtWithoutSTCN"] = LstTDSAmtWithoutSTCN;

            LstDicountCN = new List<string>();
            ViewState["LstDicountCN"] = LstDicountCN;

            LstDicountAmtCN = new List<string>();
            ViewState["LstDicountAmtCN"] = LstDicountAmtCN;

            LstWriteOffCN = new List<string>();
            ViewState["LstWriteOffCN"] = LstWriteOffCN;

            LstWriteOffAmtCN = new List<string>();
            ViewState["LstWriteOffAmtCN"] = LstWriteOffAmtCN;

            LstServiceTaxAmtCN = new List<string>();
            ViewState["LstServiceTaxAmtCN"] = LstServiceTaxAmtCN;

            LstPECessAmtCN = new List<string>();
            ViewState["LstPECessAmtCN"] = LstPECessAmtCN;

            LstHECessAmtCN = new List<string>();
            ViewState["LstHECessAmtCN"] = LstHECessAmtCN;

            LstTotalAmtCN = new List<string>();
            ViewState["LstTotalAmtCN"] = LstTotalAmtCN;
            //**********Sale Return Table******

            LstCountSR = new List<string>();
            ViewState["LstCountSR"] = LstCountSR;

            LstParticularSR = new List<string>();
            ViewState["LstParticularSR"] = LstParticularSR;

            LstServiceSR = new List<string>();
            ViewState["LstServiceSR"] = LstServiceSR;

            LstSaleReturnSR = new List<string>();
            ViewState["LstSaleReturnSR"] = LstSaleReturnSR;

            LstSaleReturnAmtSR = new List<string>();
            ViewState["LstSaleReturnAmtSR"] = LstSaleReturnAmtSR;

            LstTotalAmtSR = new List<string>();
            ViewState["LstTotalAmtSR"] = LstTotalAmtSR;

            LstHidChildCount = new List<string>();
            ViewState["LstHidChildCount"] = LstHidChildCount;

            LstHidChildID = new List<string>();
            ViewState["LstHidChildID"] = LstHidChildID;

            LstChkDelete = new List<string>();
            ViewState["LstChkDelete"] = LstChkDelete;

            LstChkDeleteSR = new List<string>();
            ViewState["LstChkDeleteSR"] = LstChkDeleteSR;

            LstChkDeleteCN = new List<string>();
            ViewState["LstChkDeleteCN"] = LstChkDeleteCN;

            LstHidRefID = new List<string>();
            ViewState["LstHidRefID"] = LstHidRefID;

             LstOldIdCounter = new List<string>();
            ViewState["LstOldIdCounter"] = LstOldIdCounter;


            if (Request.QueryString != null)
            {
                hidTranID.Value = Request.QueryString["Tranid"].ToString();
                hidCreditNoteID.Value = Request.QueryString["Creditnoteid"].ToString();
                hidVoudate.Value=Request.QueryString["Date"].ToString();
            }

             //txtDate.Text = hidVoudate.Value.ToString();
            _EnableDisableControls(ddlFormat.SelectedValue);
            _BindTransactionFormat();
            _BindCustomerLedger();
            _GetCurrentServiceTaxRate(hidVoudate.Value.ToString());
             BindCreditnoteMain();
        }
    }


    protected void BindCreditnoteMain()
    {
        ddlCustomer.Enabled = false; 
 
        if (hidVoudate.Value != string.Empty)
        {
            txtDate.Text = hidVoudate.Value.ToString();
        }
        SqlParameter[] sqlparaTran = {
                                         new SqlParameter("@tranid",hidTranID.Value.ToString())
                                     };
        DataTable dtCNDtlTranid = DU.getdatausingprocedure("USP_IVC_GetcreditnotedetailBy_Tranid", sqlparaTran);
        if (dtCNDtlTranid.Rows.Count > 0)
        {
            txtPreparedBy.Text = dtCNDtlTranid.Rows[0]["PREPAREDBY"].ToString();
            txtCheckedBy.Text = dtCNDtlTranid.Rows[0]["CHECKEDBY"].ToString();
            txtRemarks.Text = dtCNDtlTranid.Rows[0]["REMARKS"].ToString();
            string customer = dtCNDtlTranid.Rows[0]["LID"].ToString();
            txtNarration.Text = dtCNDtlTranid.Rows[0]["NARRATION"].ToString();
            txtRefNo.Text = dtCNDtlTranid.Rows[0]["REFNO"].ToString();
            ddlCustomer.SelectedValue = customer;
            string Billformat = dtCNDtlTranid.Rows[0]["BILLFORMATID"].ToString();
            ddlFormat.SelectedValue = Billformat;
            ddlFormat.Enabled = false;
            txtPrefix.Text = dtCNDtlTranid.Rows[0]["prefix"].ToString();
            txtCreditNoteNo.Text = dtCNDtlTranid.Rows[0]["VOUNO"].ToString();
            txtSuffix.Text = dtCNDtlTranid.Rows[0]["suffix"].ToString();
        }
        SqlParameter[] sqlparaCredit = {
                                         new SqlParameter("@CREDITNOTEID",hidCreditNoteID.Value.ToString())
                                     };
        DataTable dtCNDtlCredit = DU.getdatausingprocedure("USP_IVC_GetcreditnotedetailBy_CREDITNOTEID", sqlparaCredit);
        if (dtCNDtlCredit.Rows.Count > 0)
        {
            hidVouSerial.Value = dtCNDtlCredit.Rows[0]["VOUSERIAL"].ToString();
            hidRefdetails.Value = dtCNDtlCredit.Rows[0]["REFSERIAL"].ToString();

                        hidOldChildIDCount.Value = dtCNDtlCredit.Rows.Count.ToString();

            if (dtCNDtlCredit.Rows[0]["ISSALESRETURN"].ToString() == "False")
            {
                rbtCreditNoteType.SelectedValue = "0";
            }
            else
            {
                rbtCreditNoteType.SelectedValue = "1";
            }

            txtServiceTaxAmt.Text = dtCNDtlCredit.Rows[0]["SERVICETAXAMT"].ToString();
            txtPECessAmt.Text = dtCNDtlCredit.Rows[0]["EDUCESS1AMT"].ToString();
            txtHECessAmt.Text = dtCNDtlCredit.Rows[0]["EDUCESS2AMT"].ToString();

            if (dtCNDtlCredit.Rows.Count > 1)
            {
                for (int i = 1; i < dtCNDtlCredit.Rows.Count; i++)
                {
                    _AddMoreRow_MainTable();
                    Add_OLDID();
                }
            }

            for (int i = 0; i < dtCNDtlCredit.Rows.Count; i++)
            {
                DropDownList ddl = (DropDownList)tblCreditNoteMain.FindControl("ddlInvoiceParticular" + (i + 1));
                DropDownList ddlServices = (DropDownList)tblCreditNoteMain.FindControl("ddlServices" + (i + 1));
                TextBox txtOriginalAmt = (TextBox)tblCreditNoteMain.FindControl("txtOriginalAmt" + (i + 1));
                TextBox txtPendingAmt = (TextBox)tblCreditNoteMain.FindControl("txtPendingAmt" + (i + 1));
                TextBox txtamount = (TextBox)tblCreditNoteMain.FindControl("txtTotalAmount" + (i + 1));
                TextBox txtAddDescription = (TextBox)tblCreditNoteMain.FindControl("txtAddDescription" + (i + 1));
                HiddenField hidTotalAmout = (HiddenField)tblCreditNoteMain.FindControl("hidTotalAmout" + (i + 1));
                HiddenField hidServiceTaxability = (HiddenField)tblCreditNoteMain.FindControl("hidServiceTaxability" + (i + 1));
                HiddenField hidOldChildID = (HiddenField)tblOldChildID.FindControl("hidOldChildID" + (i + 1));
                HiddenField hidRefID = (HiddenField)tblOldChildID.FindControl("hidRefID" + (i + 1));

                _GetParticular_MainTable(ddl);

                ddl.SelectedValue = dtCNDtlCredit.Rows[i]["parentref"].ToString();
                DataTable DTService = _ReturnPendingService_Details();
                DataView DVService = DTService.DefaultView;
                DVService.RowFilter = "ReferenceSerial='" + dtCNDtlCredit.Rows[i]["REFSERIAL"].ToString() + "'";
                DataTable DTTempService = DVService.ToTable();

                if (DTTempService.Rows.Count > 0)
                {
                    ddlServices.DataSource = DTTempService;
                    ddlServices.DataTextField = "ServiceName";
                    ddlServices.DataValueField = "ServiceId";
                    ddlServices.DataBind();
                    ddlServices.Items.Insert(0, new ListItem("", "0"));
                }
                else
                {
                    ddlServices.Items.Clear();
                    ddlServices.Items.Insert(0, new ListItem("", "0"));
                }
                ddlServices.SelectedValue = dtCNDtlCredit.Rows[i]["SERVICEID"].ToString();
                txtamount.Text = dtCNDtlCredit.Rows[i]["AMOUNT"].ToString();

                DataTable DTParticular = _ReturnParticular();
                DataView DVParticular = DTParticular.DefaultView;
                DVParticular.RowFilter = "ReferenceId='" + ddl.SelectedValue + "'";
                DataTable DTTempParticular = DVParticular.ToTable();

                txtAddDescription.Text = dtCNDtlCredit.Rows[i]["adddesc"].ToString();

                txtOriginalAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["Amount"].ToString()));
                txtPendingAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["PendingAmount"].ToString()));
                hidTotalAmout.Value = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["PendingAmount"].ToString()));
                hidServiceTaxability.Value = _GetRembursmentService(ddl.SelectedValue);
                int rowIndex = Convert.ToInt32(ddlServices.ID.ToString().Substring(11));

                hidOldChildID.Value = dtCNDtlCredit.Rows[i]["CREDITNOTECHILDID"].ToString();
                hidRefID.Value = dtCNDtlCredit.Rows[i]["REFERENCEID"].ToString();
          
                if (dtCNDtlCredit.Rows[0]["ISSALESRETURN"].ToString() == "False")
                {
                    _AddRow_tblCreditNote(i + 1);
                    _BindDetails_tblTDSCreditNote(i + 1);
                    DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlInvoiceParticular" + rowIndex);
                   
                    TextBox txtParticularCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtParticularCN" + (i + 1));
                    TextBox txtServiceCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtServiceCN" + (i + 1));
                    TextBox txtTDSAmtCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtTDSAmtCN" + (i + 1));
                    TextBox txtDiscountCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtDiscountCN" + (i + 1));
                    TextBox txtWriteOffCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtWriteOffCN" + (i + 1));
                    TextBox txtTotalAmtCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtTotalAmtCN" + (i + 1));
                    txtTotalAmtCN.Attributes.Add("textalign", "right");
                    txtTotalAmount.Text = dtCNDtlCredit.Rows[i]["AMOUNT"].ToString();
                    txtWriteOffCN.Text = dtCNDtlCredit.Rows[i]["WRITEOFFAMT"].ToString();
                    txtDiscountCN.Text = dtCNDtlCredit.Rows[i]["DISCOUNTAMT"].ToString();
                    txtTDSAmtCN.Text = dtCNDtlCredit.Rows[i]["TDSAMOUNT"].ToString();
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "CalculateTotalCreditNoteAmt();", true);
                    panelCreditNote.Visible = true;
                    panelSalesReturn.Visible = false;
                }
                else if (dtCNDtlCredit.Rows[0]["ISSALESRETURN"].ToString() == "True")
                {
                    _AddRow_tblTDSSaleReturn(i + 1);

                    _BindDetails_tblTDSSaleReturn(i + 1);

                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "CalculateTotalSaleReturnAmt();", true);
                    panelCreditNote.Visible = false;
                    panelSalesReturn.Visible = true;
                }
            }
        }

        /* TO GET ALL RELATED ENTRIES FROM ACC_VOUDETAILS  */

        string strsql = "select * from ACC_VOUDETAILS where TRANID=" + hidTranID.Value.ToString() + " and RECDATE='" + string.Format("{0:MM/dd/yyyy}", Convert.ToDateTime(hidVoudate.Value.ToString())) + "'";
        DataTable dtFromVouDetails = DU.getdata(strsql);

        DataTable dtAllLID = new DataTable();
        dtAllLID.Columns.Add("ST_LID", typeof(string));
        dtAllLID.Columns.Add("PE_LID", typeof(string));
        dtAllLID.Columns.Add("HE_LID", typeof(string));
        dtAllLID.Columns.Add("Discount_LID", typeof(string));
        dtAllLID.Columns.Add("TDS_LID", typeof(string));
        dtAllLID.Columns.Add("Writeoff_LID", typeof(string));

        SqlParameter[] sqlparamforHOA = {
                                            new SqlParameter("@FORMATID",ddlFormat.SelectedValue),
                                        };
        DataTable dtHOA = DU.getdatausingprocedure("USP_IVC_GetTransactionFormat_HeadOfAccounts", sqlparamforHOA);

        SqlParameter[] sqlparamforSTPEHE = {
                                            new SqlParameter("@CURRENTDATE",string.Format("{0:MM/dd/yyyy}",Convert.ToDateTime(hidVoudate.Value.ToString()))),
                                        };
        DataTable dtSTHEPE = DU.getdatausingprocedure("USP_IVC_GetCurrentServiceTaxRate", sqlparamforSTPEHE);
        DataRow row = dtAllLID.NewRow();

        row["ST_LID"] = dtSTHEPE.Rows[0]["SERVICETAX_LID"].ToString();
        row["PE_LID"] = dtSTHEPE.Rows[0]["PCESS_LID"].ToString();
        row["HE_LID"] = dtSTHEPE.Rows[0]["HCESS_LID"].ToString();
        row["Discount_LID"] = dtHOA.Rows[0]["DISCOUNT_LEDGERID"].ToString();
        row["TDS_LID"] = dtHOA.Rows[0]["TDS_LEDGERID"].ToString();
        row["Writeoff_LID"] = dtHOA.Rows[0]["WRITEOFF_LEDGERID"].ToString();
        dtAllLID.Rows.Add(row);

        DataTable dtVouLidDetails = new DataTable();
        dtVouLidDetails.Columns.Add("Vouserial",typeof(string));
        dtVouLidDetails.Columns.Add("LName",typeof(string));
        dtVouLidDetails.Columns.Add("LID",typeof(string));
       

        int totalRowCount = dtFromVouDetails.Rows.Count;
        int ChildRowCount = dtCNDtlCredit.Rows.Count;
        int Countfor_ForLoop = totalRowCount - (ChildRowCount + 1);
        for (int s = ChildRowCount + 1; s < totalRowCount; s++)
        {
            DataRow dtVouRow = dtVouLidDetails.NewRow();
            dtVouRow["Vouserial"] = dtFromVouDetails.Rows[s]["VOUSERIAL"].ToString();
            dtVouRow["LID"] = dtFromVouDetails.Rows[s]["LID"].ToString();

            string strLID = dtFromVouDetails.Rows[s]["LID"].ToString();
            if (hidOldTdsLid.Value == string.Empty)
            {
                if (dtAllLID.Rows[0]["TDS_LID"].ToString() == strLID)
                {
                    hidOldTdsLid.Value = strLID;
                    dtVouRow["LName"] = "TDS_LID";
                    dtVouLidDetails.Rows.Add(dtVouRow);
                    continue;
                }
            }
            if (hidOldWriteOff.Value == string.Empty)
            {
                if (dtAllLID.Rows[0]["Writeoff_LID"].ToString() == strLID)
                {
                    hidOldWriteOff.Value = strLID;
                    dtVouRow["LName"] = "Writeoff_LID";
                    dtVouLidDetails.Rows.Add(dtVouRow);
                    continue;
                }
            }
            if (hidSTLid.Value == string.Empty)
            {
                if (dtAllLID.Rows[0]["ST_LID"].ToString() == strLID)
                {
                    hidSTLid.Value = strLID;
                    dtVouRow["LName"] = "ST_LID";
                    dtVouLidDetails.Rows.Add(dtVouRow);
                    continue;
                }
            }
            if (hidPELid.Value == string.Empty)
            {
                if (dtAllLID.Rows[0]["PE_LID"].ToString() == strLID)
                {
                    hidPELid.Value = strLID;
                    dtVouRow["LName"] = "PE_LID";
                    dtVouLidDetails.Rows.Add(dtVouRow);
                    continue;
                }
            }
            if (hidHELid.Value == string.Empty)
            {
                if (dtAllLID.Rows[0]["HE_LID"].ToString() == strLID)
                {
                    hidHELid.Value = strLID;
                    dtVouRow["LName"] = "HE_LID";
                    dtVouLidDetails.Rows.Add(dtVouRow);
                    continue;
                }
            }
            //dtVouLidDetails.Rows.Add(dtVouRow);
        }
        Session["dtVouLidDetails"] = dtVouLidDetails;
    }


    private void _BindTransactionFormat()
    {
        SqlParameter[] sparam ={
                                   new SqlParameter("@TRANSACTIONTYPE","4")
                               };
        DataTable DTFormat = DU.getdatausingprocedure("USP_IVC_GetAllTransactionFormatNameID", sparam);
        if (DTFormat.Rows.Count > 0)
        {
            ddlFormat.DataSource = DTFormat;
            ddlFormat.DataTextField = "FORMATNAME";
            ddlFormat.DataValueField = "FORMATID";
            ddlFormat.DataBind();
        }
    }
    private void _BindCustomerLedger()
    {
        DataTable DTFormat = DU.getdatausingprocedure("USP_IVC_GetCustomerLedger");
        if (DTFormat.Rows.Count > 0)
        {
            ddlCustomer.DataSource = DTFormat;
            ddlCustomer.DataTextField = "LNAME";
            ddlCustomer.DataValueField = "LID";
            ddlCustomer.DataBind();
            ddlCustomer.Items.Insert(0, new ListItem("-Select Customer-", "0"));
        }
    }
    private void _GetCurrentServiceTaxRate(string strCurrentDate)
    {
        if (strCurrentDate != string.Empty)
        {
            string[] strTemp = strCurrentDate.ToString().Split('/');
            string strDate = strTemp[1] + "/" + strTemp[0] + "/" + strTemp[2];

            SqlParameter[] sparam ={
                                       new SqlParameter("@CURRENTDATE",strDate)
                                   };
            DataTable DTCurrentST = DU.getdatausingprocedure("USP_IVC_GetCurrentServiceTaxRate", sparam);
            if (DTCurrentST.Rows.Count > 0)
            {
                txtServiceTaxPer.Text = string.Format("{0:0.00}", Convert.ToDouble(DTCurrentST.Rows[0]["ServiceTax"].ToString())).ToString();
                txtPECessPer.Text = string.Format("{0:0.00}", Convert.ToDouble(DTCurrentST.Rows[0]["PCess"].ToString())).ToString();
                txtHECessPer.Text = string.Format("{0:0.00}", Convert.ToDouble(DTCurrentST.Rows[0]["HCess"].ToString())).ToString();

                hidServiceTaxRateCurrent.Value = string.Format("{0:0.00}", Convert.ToDouble(DTCurrentST.Rows[0]["SERVICETAX"].ToString()));
                hidPECessRateCurrent.Value = string.Format("{0:0.00}", Convert.ToDouble(DTCurrentST.Rows[0]["PCess"].ToString()));
                hidHECessRateCurrent.Value = string.Format("{0:0.00}", Convert.ToDouble(DTCurrentST.Rows[0]["HCess"].ToString()));

                hidServiceTaxLid.Value = DTCurrentST.Rows[0]["SERVICETAX_LID"].ToString();
                hidPECessLid.Value = DTCurrentST.Rows[0]["PCess_LID"].ToString();
                hidHECessLid.Value = DTCurrentST.Rows[0]["HCess_LID"].ToString();
            }
        }
    }


    private void _AddMoreRow_MainTable()
    {
        intRowCounter++;
        HtmlTableRow HTRow = new HtmlTableRow();

        HtmlTableCell HTCell0 = new HtmlTableCell();
        HTCell0.Align = "center";
        CheckBox chkDelete = new CheckBox();
        chkDelete.ID = "chkDelete" + intRowCounter.ToString();
        chkDelete.Width = Unit.Percentage(98);
        chkDelete.Attributes.Add("onclick", "checkAlLChecked();");
        HTCell0.Controls.Add(chkDelete);
        LstChkDelete.Add(chkDelete.ID);

        HtmlTableCell HTCell1 = new HtmlTableCell();
        DropDownList ddlInvoiceParticular = new DropDownList();
        ddlInvoiceParticular.ID = "ddlInvoiceParticular" + intRowCounter.ToString();
        ddlInvoiceParticular.CssClass = "dropdown";
        ddlInvoiceParticular.Width = Unit.Percentage(98);
        _GetParticular_MainTable(ddlInvoiceParticular);
        ddlInvoiceParticular.AutoPostBack = true;
        ddlInvoiceParticular.SelectedIndexChanged += new EventHandler(ddlParticular_OnSelectedIndexChanged);
        HiddenField hidServiceTaxRate = new HiddenField();
        hidServiceTaxRate.ID = "hidServiceTaxRate" + intRowCounter.ToString();
        HiddenField hidPECessRate = new HiddenField();
        hidPECessRate.ID = "hidPECessRate" + intRowCounter.ToString();
        HiddenField hidHECessRate = new HiddenField();
        hidHECessRate.ID = "hidHECessRate" + intRowCounter.ToString();

        HTCell1.Controls.Add(ddlInvoiceParticular);
        HTCell1.Controls.Add(hidServiceTaxRate);
        HTCell1.Controls.Add(hidPECessRate);
        HTCell1.Controls.Add(hidHECessRate);

        LstCount.Add(intRowCounter.ToString());
        LstInvoiceParticular.Add(ddlInvoiceParticular.ID);
        LstServiceTaxRate.Add(hidServiceTaxRate.ID);
        LstPECessRate.Add(hidPECessRate.ID);
        LstHECessRate.Add(hidHECessRate.ID);

        HtmlTableCell HTCell2 = new HtmlTableCell();
        DropDownList ddlServices = new DropDownList();
        ddlServices.ID = "ddlServices" + intRowCounter.ToString();
        ddlServices.CssClass = "dropdown";
        ddlServices.Width = Unit.Percentage(98);
        ddlServices.AutoPostBack = true;
        ddlServices.Attributes.Add("onchange", "return NoServiceRepeat(this.id);");
        ddlServices.SelectedIndexChanged += new EventHandler(ddlServiecs_OnSelectedIndexChanged);

        HiddenField hidServiceTaxability = new HiddenField();
        hidServiceTaxability.ID = "hidServiceTaxability" + intRowCounter.ToString();
        HTCell2.Controls.Add(ddlServices);
        HTCell2.Controls.Add(hidServiceTaxability);
        LstService.Add(ddlServices.ID);
        LstServiceTaxability.Add(hidServiceTaxability.ID);

        HtmlTableCell HTCell3 = new HtmlTableCell();
        TextBox txtOriginalAmt = new TextBox();
        txtOriginalAmt.ID = "txtOriginalAmt" + intRowCounter.ToString();
        txtOriginalAmt.CssClass = "DisableInputNumber";
        txtOriginalAmt.Width = Unit.Percentage(98);
        txtOriginalAmt.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
        HTCell3.Controls.Add(txtOriginalAmt);
        LstOriginalAmt.Add(txtOriginalAmt.ID);

        HtmlTableCell HTCell4 = new HtmlTableCell();
        TextBox txtPendingAmt = new TextBox();
        txtPendingAmt.ID = "txtPendingAmt" + intRowCounter.ToString();
        txtPendingAmt.CssClass = "DisableInputNumber";
        txtPendingAmt.Width = Unit.Percentage(98);
        txtPendingAmt.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
        HTCell4.Controls.Add(txtPendingAmt);
        LstPendingAmt.Add(txtPendingAmt.ID);

        HtmlTableCell HTCell5 = new HtmlTableCell();
        TextBox txtAddDescription = new TextBox();
        txtAddDescription.ID = "txtAddDescription" + intRowCounter.ToString();
        txtAddDescription.CssClass = "input";
        txtAddDescription.Width = Unit.Percentage(98);
        HTCell5.Controls.Add(txtAddDescription);
        LstAddDescription.Add(txtAddDescription.ID);

        HtmlTableCell HTCell6 = new HtmlTableCell();
        TextBox txtTotalAmount = new TextBox();
        txtTotalAmount.ID = "txtTotalAmount" + intRowCounter.ToString();
        txtTotalAmount.CssClass = "DisableInputNumber";
        txtTotalAmount.BackColor = System.Drawing.Color.White;
         //txtPendingAmt.CssClass = "DisableInputNumber";
        txtTotalAmount.Width = Unit.Percentage(98);
        txtTotalAmount.Attributes.Add("onkeypress", "return isNumberKey(this.id, event);");
        txtTotalAmount.Attributes.Add("onblur", "return SetAmount(this.id);");
        HiddenField hidTotalAmout = new HiddenField();
        hidTotalAmout.ID = "hidTotalAmout" + intRowCounter.ToString();

        HTCell6.Controls.Add(txtTotalAmount);
        HTCell6.Controls.Add(hidTotalAmout);
        LstTotalAmount.Add(txtTotalAmount.ID);
        LstHiddenTotalAmount.Add(hidTotalAmout.ID);


        HTRow.Cells.Add(HTCell0); 
        HTRow.Cells.Add(HTCell1);
        HTRow.Cells.Add(HTCell2);
        HTRow.Cells.Add(HTCell3);
        HTRow.Cells.Add(HTCell4);
        HTRow.Cells.Add(HTCell5);
        HTRow.Cells.Add(HTCell6);

        tblCreditNoteMain.Rows.Add(HTRow);


        ViewState["LstCount"] = LstCount;
        ViewState["LstInvoiceParticular"] = LstInvoiceParticular;
        ViewState["LstServiceTaxRate"] = LstServiceTaxRate;
        ViewState["LstPECessRate"] = LstPECessRate;
        ViewState["LstHECessRate"] = LstHECessRate;
        ViewState["LstService"] = LstService;
        ViewState["LstServiceTaxability"] = LstServiceTaxability;
        ViewState["LstOriginalAmt"] = LstOriginalAmt;
        ViewState["LstPendingAmt"] = LstPendingAmt;
        ViewState["LstAddDescription"] = LstAddDescription;
        ViewState["LstTotalAmount"] = LstTotalAmount;
        ViewState["LstHiddenTotalAmount"] = LstHiddenTotalAmount;
        ViewState["LstChkDelete"] = LstChkDelete;

        hidRowCountMain.Value = intRowCounter.ToString();
    }

    private void _Override_AddMoreRow_MainTable()
    {
        LstCount = (List<string>)ViewState["LstCount"];
        LstInvoiceParticular = (List<string>)ViewState["LstInvoiceParticular"];
        LstServiceTaxRate = (List<string>)ViewState["LstServiceTaxRate"];
        LstPECessRate = (List<string>)ViewState["LstPECessRate"];
        LstHECessRate = (List<string>)ViewState["LstHECessRate"];
        LstService = (List<string>)ViewState["LstService"];
        LstServiceTaxability = (List<string>)ViewState["LstServiceTaxability"];
        LstOriginalAmt = (List<string>)ViewState["LstOriginalAmt"];
        LstPendingAmt = (List<string>)ViewState["LstPendingAmt"];
        LstAddDescription = (List<string>)ViewState["LstAddDescription"];
        LstTotalAmount = (List<string>)ViewState["LstTotalAmount"];
        LstHiddenTotalAmount = (List<string>)ViewState["LstHiddenTotalAmount"];
        LstChkDelete = (List<string>)ViewState["LstChkDelete"];

        if (LstCount != null)
        {
            int intCount = Convert.ToInt32(LstCount.Count);
            for (int i = 0; i < intCount; i++)
            {
                intRowCounter++;
                HtmlTableRow HTRow = new HtmlTableRow();


                HtmlTableCell HTCell0 = new HtmlTableCell();
                HTCell0.Align = "Center";

                CheckBox chkDelete = new CheckBox();
                chkDelete.ID = LstChkDelete[i].ToString();
                chkDelete.Width = Unit.Percentage(98);
                chkDelete.Attributes.Add("onclick", "checkAlLChecked();");
                HTCell0.Controls.Add(chkDelete);

                HtmlTableCell HTCell1 = new HtmlTableCell();
                DropDownList ddlInvoiceParticular = new DropDownList();
                ddlInvoiceParticular.ID = LstInvoiceParticular[i].ToString();
                ddlInvoiceParticular.CssClass = "dropdown";
                ddlInvoiceParticular.Width = Unit.Percentage(98);
                _GetParticular_MainTable(ddlInvoiceParticular);
                ddlInvoiceParticular.AutoPostBack = true;
                ddlInvoiceParticular.SelectedIndexChanged += new EventHandler(ddlParticular_OnSelectedIndexChanged);
                HiddenField hidServiceTaxRate = new HiddenField();
                hidServiceTaxRate.ID = LstServiceTaxRate[i].ToString();
                HiddenField hidPECessRate = new HiddenField();
                hidPECessRate.ID = LstPECessRate[i].ToString();
                HiddenField hidHECessRate = new HiddenField();
                hidHECessRate.ID = LstHECessRate[i].ToString();

                HTCell1.Controls.Add(ddlInvoiceParticular);
                HTCell1.Controls.Add(hidServiceTaxRate);
                HTCell1.Controls.Add(hidPECessRate);
                HTCell1.Controls.Add(hidHECessRate);

                HtmlTableCell HTCell2 = new HtmlTableCell();
                DropDownList ddlServices = new DropDownList();
                ddlServices.ID = LstService[i].ToString();
                ddlServices.CssClass = "dropdown";
                ddlServices.Width = Unit.Percentage(98);
                ddlServices.AutoPostBack = true;
                ddlServices.Attributes.Add("onchange", "return NoServiceRepeat(this.id);");
                ddlServices.SelectedIndexChanged += new EventHandler(ddlServiecs_OnSelectedIndexChanged);

                HiddenField hidServiceTaxability = new HiddenField();
                hidServiceTaxability.ID = LstServiceTaxability[i].ToString();
                HTCell2.Controls.Add(ddlServices);
                HTCell2.Controls.Add(hidServiceTaxability);


                HtmlTableCell HTCell3 = new HtmlTableCell();
                TextBox txtOriginalAmt = new TextBox();
                txtOriginalAmt.ID = LstOriginalAmt[i].ToString();
                txtOriginalAmt.CssClass = "DisableInputNumber";
                txtOriginalAmt.Width = Unit.Percentage(98);
                txtOriginalAmt.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
                HTCell3.Controls.Add(txtOriginalAmt);

                HtmlTableCell HTCell4 = new HtmlTableCell();
                TextBox txtPendingAmt = new TextBox();
                txtPendingAmt.ID = LstPendingAmt[i].ToString();
                txtPendingAmt.CssClass = "DisableInputNumber";
                txtPendingAmt.Width = Unit.Percentage(98);
                txtPendingAmt.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
                HTCell4.Controls.Add(txtPendingAmt);


                HtmlTableCell HTCell5 = new HtmlTableCell();
                TextBox txtAddDescription = new TextBox();
                txtAddDescription.ID = LstAddDescription[i].ToString();
                txtAddDescription.CssClass = "input";
                txtAddDescription.Width = Unit.Percentage(98);
                HTCell5.Controls.Add(txtAddDescription);


                HtmlTableCell HTCell6 = new HtmlTableCell();
                TextBox txtTotalAmount = new TextBox();
                txtTotalAmount.ID = LstTotalAmount[i].ToString();
                txtTotalAmount.CssClass = "inputnumber";
                txtTotalAmount.Width = Unit.Percentage(98);
                txtTotalAmount.Attributes.Add("onkeypress", "return isNumberKey(this.id, event);");
                txtTotalAmount.Attributes.Add("onblur", "return SetAmount(this.id);");
                HiddenField hidTotalAmout = new HiddenField();
                hidTotalAmout.ID = LstHiddenTotalAmount[i].ToString();

                HTCell6.Controls.Add(txtTotalAmount);
                HTCell6.Controls.Add(hidTotalAmout);

                HTRow.Cells.Add(HTCell0);
                HTRow.Cells.Add(HTCell1);
                HTRow.Cells.Add(HTCell2);
                HTRow.Cells.Add(HTCell3);
                HTRow.Cells.Add(HTCell4);
                HTRow.Cells.Add(HTCell5);
                HTRow.Cells.Add(HTCell6);

                tblCreditNoteMain.Rows.Add(HTRow);
            }
        }
    }
    private void _DeleteAllRow_MainTable()
    {
        int rowCount = Convert.ToInt32(hidRowCountMain.Value);
        int rowIndex = rowCount;
        int tblRowCount = Convert.ToInt32(tblCreditNoteMain.Rows.Count);
        if (tblRowCount > 2)
        {
            for (int i = tblRowCount; i > 2; i--)
            {
                LstCount = (List<string>)ViewState["LstCount"];
                LstInvoiceParticular = (List<string>)ViewState["LstInvoiceParticular"];
                LstServiceTaxRate = (List<string>)ViewState["LstServiceTaxRate"];
                LstPECessRate = (List<string>)ViewState["LstPECessRate"];
                LstHECessRate = (List<string>)ViewState["LstHECessRate"];
                LstService = (List<string>)ViewState["LstService"];
                LstServiceTaxability = (List<string>)ViewState["LstServiceTaxability"];
                LstOriginalAmt = (List<string>)ViewState["LstOriginalAmt"];
                LstPendingAmt = (List<string>)ViewState["LstPendingAmt"];
                LstAddDescription = (List<string>)ViewState["LstAddDescription"];
                LstTotalAmount = (List<string>)ViewState["LstTotalAmount"];
                LstHiddenTotalAmount = (List<string>)ViewState["LstHiddenTotalAmount"];

                tblCreditNoteMain.Rows.RemoveAt(i - 1);

                LstCount.RemoveAt(i - 3);
                LstInvoiceParticular.RemoveAt(i - 3);
                LstServiceTaxRate.RemoveAt(i - 3);
                LstPECessRate.RemoveAt(i - 3);
                LstHECessRate.RemoveAt(i - 3);
                LstService.RemoveAt(i - 3);
                LstServiceTaxability.RemoveAt(i - 3);
                LstOriginalAmt.RemoveAt(i - 3);
                LstPendingAmt.RemoveAt(i - 3);
                LstAddDescription.RemoveAt(i - 3);
                LstTotalAmount.RemoveAt(i - 3);
                LstHiddenTotalAmount.RemoveAt(i - 3);

                ViewState["LstCount"] = LstCount;
                ViewState["LstInvoiceParticular"] = LstInvoiceParticular;
                ViewState["LstServiceTaxRate"] = LstServiceTaxRate;
                ViewState["LstPECessRate"] = LstPECessRate;
                ViewState["LstHECessRate"] = LstHECessRate;
                ViewState["LstService"] = LstService;
                ViewState["LstServiceTaxability"] = LstServiceTaxability;
                ViewState["LstOriginalAmt"] = LstOriginalAmt;
                ViewState["LstPendingAmt"] = LstPendingAmt;
                ViewState["LstAddDescription"] = LstAddDescription;
                ViewState["LstTotalAmount"] = LstTotalAmount;
                ViewState["LstHiddenTotalAmount"] = LstHiddenTotalAmount;

                hidRowCountMain.Value = "1";
            }
        }
    }
    private void _DeleteAllRow_Details()
    {
        if (tblTdsCreditNote.Rows.Count > 1)
        {
            for (int i = tblTdsCreditNote.Rows.Count; i > 1; i--)
            {
                LstCountCN = (List<string>)ViewState["LstCountCN"];
                LstParticularCN = (List<string>)ViewState["LstParticularCN"];
                LstServiceCN = (List<string>)ViewState["LstServiceCN"];
                LstTDSAmtCN = (List<string>)ViewState["LstTDSAmtCN"];
                LstTDSAmtWithoutSTCN = (List<string>)ViewState["LstTDSAmtWithoutSTCN"];
                LstDicountCN = (List<string>)ViewState["LstDicountCN"];
                LstDicountAmtCN = (List<string>)ViewState["LstDicountAmtCN"];
                LstWriteOffCN = (List<string>)ViewState["LstWriteOffCN"];
                LstWriteOffAmtCN = (List<string>)ViewState["LstWriteOffAmtCN"];
                LstServiceTaxAmtCN = (List<string>)ViewState["LstServiceTaxAmtCN"];
                LstPECessAmtCN = (List<string>)ViewState["LstPECessAmtCN"];
                LstHECessAmtCN = (List<string>)ViewState["LstHECessAmtCN"];
                LstTotalAmtCN = (List<string>)ViewState["LstTotalAmtCN"];

                tblTdsCreditNote.Rows.RemoveAt(i - 1);

                LstCountCN.RemoveAt(i - 2);
                LstParticularCN.RemoveAt(i - 2);
                LstServiceCN.RemoveAt(i - 2);
                LstTDSAmtCN.RemoveAt(i - 2);
                LstTDSAmtWithoutSTCN.RemoveAt(i - 2);
                LstDicountCN.RemoveAt(i - 2);
                LstDicountAmtCN.RemoveAt(i - 2);
                LstWriteOffCN.RemoveAt(i - 2);
                LstWriteOffAmtCN.RemoveAt(i - 2);
                LstServiceTaxAmtCN.RemoveAt(i - 2);
                LstPECessAmtCN.RemoveAt(i - 2);
                LstHECessAmtCN.RemoveAt(i - 2);
                LstTotalAmtCN.RemoveAt(i - 2);


                ViewState["LstCountCN"] = LstCountCN;
                ViewState["LstParticularCN"] = LstParticularCN;
                ViewState["LstServiceCN"] = LstServiceCN;
                ViewState["LstTDSAmtCN"] = LstTDSAmtCN;
                ViewState["LstTDSAmtWithoutSTCN"] = LstTDSAmtWithoutSTCN;
                ViewState["LstDicountCN"] = LstDicountCN;
                ViewState["LstDicountAmtCN"] = LstDicountAmtCN;
                ViewState["LstWriteOffCN"] = LstWriteOffCN;
                ViewState["LstWriteOffAmtCN"] = LstWriteOffAmtCN;
                ViewState["LstServiceTaxAmtCN"] = LstServiceTaxAmtCN;
                ViewState["LstPECessAmtCN"] = LstPECessAmtCN;
                ViewState["LstHECessAmtCN"] = LstHECessAmtCN;
                ViewState["LstTotalAmtCN"] = LstTotalAmtCN;

                hidRowCountCN.Value = "0";
            }
        }
        if (tblTDSSaleReturn.Rows.Count > 1)
        {
            for (int i = tblTDSSaleReturn.Rows.Count; i > 1; i--)
            {
                LstCountSR = (List<string>)ViewState["LstCountSR"];
                LstParticularSR = (List<string>)ViewState["LstParticularSR"];
                LstServiceSR = (List<string>)ViewState["LstServiceSR"];
                LstSaleReturnSR = (List<string>)ViewState["LstSaleReturnSR"];
                LstTotalAmtSR = (List<string>)ViewState["LstTotalAmtSR"]; ;

                tblTDSSaleReturn.Rows.RemoveAt(i - 1);

                LstCountSR.RemoveAt(i - 2);
                LstParticularSR.RemoveAt(i - 2);
                LstServiceSR.RemoveAt(i - 2);
                LstSaleReturnSR.RemoveAt(i - 2);
                LstTotalAmtSR.RemoveAt(i - 2);

                ViewState["LstCountSR"] = LstCountSR;
                ViewState["LstParticularSR"] = LstParticularSR;
                ViewState["LstServiceSR"] = LstServiceSR;
                ViewState["LstSaleReturnSR"] = LstSaleReturnSR;
                ViewState["LstTotalAmtSR"] = LstTotalAmtSR;

                hidRowCountSR.Value = "0";
            }
        }
    }
    private void _BindDetails_tblTDSCreditNote(int rowIndex)
    {
        DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlInvoiceParticular" + rowIndex);
        TextBox txtTotalAmount = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtTotalAmount" + rowIndex);
        DropDownList ddlServices = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlServices" + rowIndex);

        TextBox txtParticularCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtParticularCN" + rowIndex);
        TextBox txtServiceCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtServiceCN" + rowIndex);
        TextBox txtTDSAmtCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtTDSAmtCN" + rowIndex);
        TextBox txtDiscountCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtDiscountCN" + rowIndex);
        TextBox txtWriteOffCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtWriteOffCN" + rowIndex);
        TextBox txtTotalAmtCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtTotalAmtCN" + rowIndex);
        //Response.Write("txtParticularCN=" + txtParticularCN.ID.ToString());
        txtParticularCN.Text = ddlInvoiceParticular.SelectedItem.Text;
        txtServiceCN.Text = ddlServices.SelectedItem.Text;
        string strTaxability = _GetRembursmentService(ddlServices.SelectedValue);
        if (strTaxability == "1")
        {
            txtDiscountCN.Text = "";
            txtTDSAmtCN.Enabled = true;
            txtTDSAmtCN.Text = txtTotalAmount.Text;
            txtTDSAmtCN.CssClass = "inputnumber";
        }
        else
        {
            txtDiscountCN.Text = txtTotalAmount.Text;
            txtTDSAmtCN.Text = "";
            txtTDSAmtCN.Enabled = false;
            txtTDSAmtCN.CssClass = "DisableInputNumber";
        }
        txtTotalAmtCN.Text = txtTotalAmount.Text;
    }
    private void _BindDetails_tblTDSSaleReturn(int rowIndex)
    {
        DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlInvoiceParticular" + rowIndex);
        TextBox txtTotalAmount = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtTotalAmount" + rowIndex);
        DropDownList ddlServices = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlServices" + rowIndex);

        TextBox txtParticularSR = (TextBox)tblTDSSaleReturn.Rows[rowIndex].FindControl("txtParticularSR" + rowIndex);
        TextBox txtServiceSR = (TextBox)tblTDSSaleReturn.Rows[rowIndex].FindControl("txtServiceSR" + rowIndex);
        TextBox txtSaleReturnSR = (TextBox)tblTDSSaleReturn.Rows[rowIndex].FindControl("txtSaleReturnSR" + rowIndex);
        TextBox txtTotalAmtSR = (TextBox)tblTDSSaleReturn.Rows[rowIndex].FindControl("txtTotalAmtSR" + rowIndex);

        txtParticularSR.Text = ddlInvoiceParticular.SelectedItem.Text;
        txtServiceSR.Text = ddlServices.SelectedItem.Text;
        txtSaleReturnSR.Text = txtTotalAmount.Text;
        txtTotalAmtSR.Text = txtTotalAmount.Text;
    }
    private DataTable _ReturnParticular()
    {
        string strTranDate = string.Empty;
        DataTable DTParticular = new DataTable();
        if (txtDate.Text != string.Empty)
        {
            string[] str = txtDate.Text.Split('/');
            strTranDate = str[1] + "/" + str[0] + "/" + str[2];
        }
        if (ddlCustomer.SelectedValue != "0" && strTranDate != string.Empty)
        {
          //  Response.Write("LID=" + ddlCustomer.SelectedValue + "VOUDATE=" + strTranDate + "ISSALES=" + rbtCreditNoteType.SelectedValue+"Finyear="+Session["FINYEAR"].ToString());
            SqlParameter[] sparam ={
                                   new SqlParameter("@LID",ddlCustomer.SelectedValue),
                                   new SqlParameter("@VOUDATE",strTranDate),
                                   new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString()),
                                   new SqlParameter("@CURRENTTRANID",hidTranID.Value.ToString()),
                                   new SqlParameter("@ISSALESRETURN",rbtCreditNoteType.SelectedValue)
                               };
            DTParticular = DU.getdatausingprocedure("USP_IVC_GetPendingParticulars", sparam);
            //Response.Write("DTPARTICULAR ROWCOUNT=" + DTParticular.Rows.Count);
        }
       // Response.Write("DTPARTICULAR ROWCOUNT="+DTParticular.Rows.Count);
        return DTParticular;
    }
    private DataTable _ReturnPendingService_Details()
    {
        string strTranDate = string.Empty;
        DataTable DTServiceDetails = new DataTable();
        if (txtDate.Text != string.Empty)
        {
            string[] str = txtDate.Text.Split('/');
            strTranDate = str[1] + "/" + str[0] + "/" + str[2];
        }
        if (ddlCustomer.SelectedValue != "0" && strTranDate != string.Empty)
        {
            SqlParameter[] sparam ={
                                   new SqlParameter("@CUSTOMERLEDGERID",ddlCustomer.SelectedValue),
                                   new SqlParameter("@VOUDATE",strTranDate),                                   
                                   new SqlParameter("@TRANID","0"),
                                   new SqlParameter("@ISSALESRETURN",rbtCreditNoteType.SelectedValue)
                               };
            DTServiceDetails = DU.getdatausingprocedure("USP_IVC_GetAllPendingServiceDetails", sparam);
        }
        return DTServiceDetails;
    }
    private DataTable _GetBilledServiceTaxRate(string strTranId)
    {
        DataTable DTServiceTax = new DataTable();
        if (strTranId != string.Empty)
        {
            SqlParameter[] sparam ={                                  
                                   new SqlParameter("@TRAINID",strTranId)
                               };
            DTServiceTax = DU.getdatausingprocedure("USP_IVC_GetTransactionServiceRates", sparam);
        }
        return DTServiceTax;
    }
    private void _GetParticular_MainTable(DropDownList ddl)
    {
        DataTable DTParticular = _ReturnParticular();
        //Response.Write("DTParticular RowCount=" + DTParticular.Rows.Count);

        ddl.DataSource = DTParticular;
        ddl.DataTextField = "Reference";
        ddl.DataValueField = "ReferenceId";
        ddl.DataBind();
        ddl.Items.Insert(0, new ListItem("", "0"));
    }
    private void _AddRow_tblCreditNote(int RowCount)
    {
        if (tblTdsCreditNote.Rows.Count == RowCount)
        {
            HtmlTableRow HTRow = new HtmlTableRow();

            HtmlTableCell HTCell0 = new HtmlTableCell();
            HTCell0.Align = "center";
            CheckBox chkDeleteCN = new CheckBox();
            chkDeleteCN.ID = "chkDeleteCN" + RowCount.ToString();
            chkDeleteCN.Width = Unit.Percentage(98);
//chkDeleteCN.Attributes.Add("onclick", "checkAlLChecked();");
            chkDeleteCN.Enabled = false;
            HTCell0.Controls.Add(chkDeleteCN);
            LstChkDeleteCN.Add(chkDeleteCN.ID);

            HtmlTableCell HTCell1 = new HtmlTableCell();
            TextBox txtParticularCN = new TextBox();
            txtParticularCN.ID = "txtParticularCN" + RowCount.ToString();
            txtParticularCN.CssClass = "DisableInput";
            txtParticularCN.Width = Unit.Percentage(98);
            txtParticularCN.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
            HTCell1.Controls.Add(txtParticularCN);
            LstCountCN.Add(RowCount.ToString());
            LstParticularCN.Add(txtParticularCN.ID);

            HtmlTableCell HTCell2 = new HtmlTableCell();
            TextBox txtServiceCN = new TextBox();
            txtServiceCN.ID = "txtServiceCN" + RowCount.ToString();
            txtServiceCN.CssClass = "DisableInput";
            txtServiceCN.Width = Unit.Percentage(98);
            txtServiceCN.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
            HTCell2.Controls.Add(txtServiceCN);
            LstServiceCN.Add(txtServiceCN.ID);

            HtmlTableCell HTCell3 = new HtmlTableCell();
            TextBox txtTDSAmtCN = new TextBox();
            txtTDSAmtCN.ID = "txtTDSAmtCN" + RowCount.ToString();
            txtTDSAmtCN.CssClass = "inputnumber";
            txtTDSAmtCN.Width = Unit.Percentage(98);
            txtTDSAmtCN.Attributes.Add("onkeypress", "return isNumberKey(this.id, event);");
            txtTDSAmtCN.Attributes.Add("onblur", "return CalculateTdsCreditNoteAmt(this.id);");
            HiddenField hidTDSAmtWithoutSTCN = new HiddenField();
            hidTDSAmtWithoutSTCN.ID = "hidTDSAmtWithoutSTCN" + RowCount.ToString();
            HiddenField hidServiceTaxAmtCN = new HiddenField();
            hidServiceTaxAmtCN.ID = "hidServiceTaxAmtCN" + RowCount.ToString();
            HiddenField hidPECessAmtCN = new HiddenField();
            hidPECessAmtCN.ID = "hidPECessAmtCN" + RowCount.ToString();
            HiddenField hidHECessAmtCN = new HiddenField();
            hidHECessAmtCN.ID = "hidHECessAmtCN" + RowCount.ToString();
            HTCell3.Controls.Add(txtTDSAmtCN);
            HTCell3.Controls.Add(hidTDSAmtWithoutSTCN);
            HTCell3.Controls.Add(hidServiceTaxAmtCN);
            HTCell3.Controls.Add(hidPECessAmtCN);
            HTCell3.Controls.Add(hidHECessAmtCN);
            LstTDSAmtCN.Add(txtTDSAmtCN.ID);
            LstTDSAmtWithoutSTCN.Add(hidTDSAmtWithoutSTCN.ID);
            LstServiceTaxAmtCN.Add(hidServiceTaxAmtCN.ID);
            LstPECessAmtCN.Add(hidPECessAmtCN.ID);
            LstHECessAmtCN.Add(hidHECessAmtCN.ID);

            HtmlTableCell HTCell4 = new HtmlTableCell();
            TextBox txtDiscountCN = new TextBox();
            txtDiscountCN.ID = "txtDiscountCN" + RowCount.ToString();
            txtDiscountCN.CssClass = "inputnumber";
            txtDiscountCN.Width = Unit.Percentage(98);
            txtDiscountCN.Attributes.Add("onkeypress", "return isNumberKey(this.id, event);");
            txtDiscountCN.Attributes.Add("onblur", "return CalculateTdsCreditNoteAmt(this.id);");
            HiddenField hidDiscountAmtCN = new HiddenField();
            hidDiscountAmtCN.ID = "hidDiscountAmtCN" + RowCount.ToString();
            HTCell4.Controls.Add(txtDiscountCN);
            HTCell4.Controls.Add(hidDiscountAmtCN);
            LstDicountCN.Add(txtDiscountCN.ID);
            LstDicountAmtCN.Add(hidDiscountAmtCN.ID);

            HtmlTableCell HTCell5 = new HtmlTableCell();
            TextBox txtWriteOffCN = new TextBox();
            txtWriteOffCN.ID = "txtWriteOffCN" + RowCount.ToString();
            txtWriteOffCN.CssClass = "inputnumber";
            txtWriteOffCN.Width = Unit.Percentage(98);
            txtWriteOffCN.Attributes.Add("onkeypress", "return isNumberKey(this.id, event);");
            txtWriteOffCN.Attributes.Add("onblur", "return CalculateTdsCreditNoteAmt(this.id);");
            HiddenField hidWriteOffAmtCN = new HiddenField();
            hidWriteOffAmtCN.ID = "hidWriteOffAmtCN" + RowCount.ToString();
            HTCell5.Controls.Add(txtWriteOffCN);
            HTCell5.Controls.Add(hidWriteOffAmtCN);
            LstWriteOffCN.Add(txtWriteOffCN.ID);
            LstWriteOffAmtCN.Add(hidWriteOffAmtCN.ID);

            HtmlTableCell HTCell6 = new HtmlTableCell();
            TextBox txtTotalAmtCN = new TextBox();
            txtTotalAmtCN.ID = "txtTotalAmtCN" + RowCount.ToString();
            txtTotalAmtCN.CssClass = "DisableInputNumber";
            txtTotalAmtCN.Width = Unit.Percentage(98);
            txtTotalAmtCN.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
            HTCell6.Controls.Add(txtTotalAmtCN);
            LstTotalAmtCN.Add(txtTotalAmtCN.ID);

            HTRow.Cells.Add(HTCell0);
            HTRow.Cells.Add(HTCell1);
            HTRow.Cells.Add(HTCell2);
            HTRow.Cells.Add(HTCell3);
            HTRow.Cells.Add(HTCell4);
            HTRow.Cells.Add(HTCell5);
            HTRow.Cells.Add(HTCell6);
            tblTdsCreditNote.Rows.Add(HTRow);

            hidRowCountCN.Value = RowCount.ToString();

            ViewState["LstCountCN"] = LstCountCN;
            ViewState["LstChkDeleteCN"] = LstChkDeleteCN;
            ViewState["LstParticularCN"] = LstParticularCN;
            ViewState["LstServiceCN"] = LstServiceCN;
            ViewState["LstTDSAmtCN"] = LstTDSAmtCN;
            ViewState["LstTDSAmtWithoutSTCN"] = LstTDSAmtWithoutSTCN;
            ViewState["LstDicountCN"] = LstDicountCN;
            ViewState["LstDicountAmtCN"] = LstDicountAmtCN;
            ViewState["LstWriteOffCN"] = LstWriteOffCN;
            ViewState["LstWriteOffAmtCN"] = LstWriteOffAmtCN;
            ViewState["LstServiceTaxAmtCN"] = LstServiceTaxAmtCN;
            ViewState["LstPECessAmtCN"] = LstPECessAmtCN;
            ViewState["LstHECessAmtCN"] = LstHECessAmtCN;
            ViewState["LstTotalAmtCN"] = LstTotalAmtCN;
        }
    }
    private void _Override_tblCreditNote()
    {
        LstCountCN = (List<string>)ViewState["LstCountCN"];
        LstParticularCN = (List<string>)ViewState["LstParticularCN"];
        LstServiceCN = (List<string>)ViewState["LstServiceCN"];
        LstTDSAmtCN = (List<string>)ViewState["LstTDSAmtCN"];
        LstTDSAmtWithoutSTCN = (List<string>)ViewState["LstTDSAmtWithoutSTCN"];
        LstDicountCN = (List<string>)ViewState["LstDicountCN"];
        LstDicountAmtCN = (List<string>)ViewState["LstDicountAmtCN"];
        LstWriteOffCN = (List<string>)ViewState["LstWriteOffCN"];
        LstWriteOffAmtCN = (List<string>)ViewState["LstWriteOffAmtCN"];
        LstServiceTaxAmtCN = (List<string>)ViewState["LstServiceTaxAmtCN"];
        LstPECessAmtCN = (List<string>)ViewState["LstPECessAmtCN"];
        LstHECessAmtCN = (List<string>)ViewState["LstHECessAmtCN"];
        LstTotalAmtCN = (List<string>)ViewState["LstTotalAmtCN"];
        LstChkDeleteCN = (List<string>)ViewState["LstChkDeleteCN"];

        if (LstCountCN != null)
        {
            int Count = Convert.ToInt32(LstCountCN.Count);
            for (int i = 0; i < Count; i++)
            {
                HtmlTableRow HTRow = new HtmlTableRow();

                HtmlTableCell HTCell0 = new HtmlTableCell();
                HTCell0.Align = "Center";
                CheckBox chkDeleteCN = new CheckBox();
                chkDeleteCN.ID = LstChkDeleteCN[i].ToString();
                chkDeleteCN.Width = Unit.Percentage(98);
                chkDeleteCN.Enabled = false;
              //  chkDeleteCn.Attributes.Add("onclick", "checkAlLChecked();");
                HTCell0.Controls.Add(chkDeleteCN);

                HtmlTableCell HTCell1 = new HtmlTableCell();
                TextBox txtParticularCN = new TextBox();
                txtParticularCN.ID = LstParticularCN[i].ToString();
                txtParticularCN.CssClass = "DisableInput";
                txtParticularCN.Width = Unit.Percentage(98);
                txtParticularCN.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
                HTCell1.Controls.Add(txtParticularCN);

                HtmlTableCell HTCell2 = new HtmlTableCell();
                TextBox txtServiceCN = new TextBox();
                txtServiceCN.ID = LstServiceCN[i].ToString();
                txtServiceCN.CssClass = "DisableInput";
                txtServiceCN.Width = Unit.Percentage(98);
                txtServiceCN.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
                HTCell2.Controls.Add(txtServiceCN);

                HtmlTableCell HTCell3 = new HtmlTableCell();
                TextBox txtTDSAmtCN = new TextBox();
                txtTDSAmtCN.ID = LstTDSAmtCN[i].ToString();
                txtTDSAmtCN.CssClass = "inputnumber";
                txtTDSAmtCN.Width = Unit.Percentage(98);
                txtTDSAmtCN.Attributes.Add("onkeypress", "return isNumberKey(this.id, event);");
                txtTDSAmtCN.Attributes.Add("onblur", "return CalculateTdsCreditNoteAmt(this.id);");
                HiddenField hidTDSAmtWithoutSTCN = new HiddenField();
                hidTDSAmtWithoutSTCN.ID = LstTDSAmtWithoutSTCN[i].ToString();
                HiddenField hidServiceTaxAmtCN = new HiddenField();
                hidServiceTaxAmtCN.ID = LstServiceTaxAmtCN[i].ToString();
                HiddenField hidPECessAmtCN = new HiddenField();
                hidPECessAmtCN.ID = LstPECessAmtCN[i].ToString();
                HiddenField hidHECessAmtCN = new HiddenField();
                hidHECessAmtCN.ID = LstHECessAmtCN[i].ToString();
                HTCell3.Controls.Add(txtTDSAmtCN);
                HTCell3.Controls.Add(hidTDSAmtWithoutSTCN);
                HTCell3.Controls.Add(hidServiceTaxAmtCN);
                HTCell3.Controls.Add(hidPECessAmtCN);
                HTCell3.Controls.Add(hidHECessAmtCN);

                HtmlTableCell HTCell4 = new HtmlTableCell();
                TextBox txtDiscountCN = new TextBox();
                txtDiscountCN.ID = LstDicountCN[i].ToString();
                txtDiscountCN.CssClass = "inputnumber";
                txtDiscountCN.Width = Unit.Percentage(98);
                txtDiscountCN.Attributes.Add("onkeypress", "return isNumberKey(this.id, event);");
                txtDiscountCN.Attributes.Add("onblur", "return CalculateTdsCreditNoteAmt(this.id);");
                HiddenField hidDiscountAmtCN = new HiddenField();
                hidDiscountAmtCN.ID = LstDicountAmtCN[i].ToString();
                HTCell4.Controls.Add(txtDiscountCN);
                HTCell4.Controls.Add(hidDiscountAmtCN);


                HtmlTableCell HTCell5 = new HtmlTableCell();
                TextBox txtWriteOffCN = new TextBox();
                txtWriteOffCN.ID = LstWriteOffCN[i].ToString();
                txtWriteOffCN.CssClass = "inputnumber";
                txtWriteOffCN.Width = Unit.Percentage(98);
                txtWriteOffCN.Attributes.Add("onkeypress", "return isNumberKey(this.id, event);");
                txtWriteOffCN.Attributes.Add("onblur", "return CalculateTdsCreditNoteAmt(this.id);");
                HiddenField hidWriteOffAmtCN = new HiddenField();
                hidWriteOffAmtCN.ID = LstWriteOffAmtCN[i].ToString();
                HTCell5.Controls.Add(txtWriteOffCN);
                HTCell5.Controls.Add(hidWriteOffAmtCN);


                HtmlTableCell HTCell6 = new HtmlTableCell();
                TextBox txtTotalAmtCN = new TextBox();
                txtTotalAmtCN.ID = LstTotalAmtCN[i].ToString();
                txtTotalAmtCN.CssClass = "DisableInputNumber";
                txtTotalAmtCN.Width = Unit.Percentage(98);
                txtTotalAmtCN.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
                HTCell6.Controls.Add(txtTotalAmtCN);

                HTRow.Cells.Add(HTCell0);
                HTRow.Cells.Add(HTCell1);
                HTRow.Cells.Add(HTCell2);
                HTRow.Cells.Add(HTCell3);
                HTRow.Cells.Add(HTCell4);
                HTRow.Cells.Add(HTCell5);
                HTRow.Cells.Add(HTCell6);
                tblTdsCreditNote.Rows.Add(HTRow);
            }
        }
    }
    private void _AddRow_tblTDSSaleReturn(int RowCount)
    {
        if (tblTDSSaleReturn.Rows.Count == RowCount)
        {
            LstCountSR.Add(RowCount.ToString());
            HtmlTableRow HTRow = new HtmlTableRow();

            HtmlTableCell HTCell0 = new HtmlTableCell();
            HTCell0.Align = "center";
            CheckBox chkDeleteSR = new CheckBox();
            chkDeleteSR.ID = "chkDeleteSR" + RowCount.ToString();
            chkDeleteSR.Width = Unit.Percentage(98);
            chkDeleteSR.Enabled = false;
//chkDeleteSR.Attributes.Add("onclick", "checkAlLChecked();");
            HTCell0.Controls.Add(chkDeleteSR);
            LstChkDeleteSR.Add(chkDeleteSR.ID);

            HtmlTableCell HTCell1 = new HtmlTableCell();
            TextBox txtParticularSR = new TextBox();
            txtParticularSR.ID = "txtParticularSR" + RowCount.ToString();
            txtParticularSR.CssClass = "DisableInput";
            txtParticularSR.Width = Unit.Percentage(98);
            txtParticularSR.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
            HTCell1.Controls.Add(txtParticularSR);
           
            LstParticularSR.Add(txtParticularSR.ID);

            HtmlTableCell HTCell2 = new HtmlTableCell();
            TextBox txtServiceSR = new TextBox();
            txtServiceSR.ID = "txtServiceSR" + RowCount.ToString();
            txtServiceSR.CssClass = "DisableInput";
            txtServiceSR.Width = Unit.Percentage(98);
            txtServiceSR.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
            HTCell2.Controls.Add(txtServiceSR);
            LstServiceSR.Add(txtServiceSR.ID);

            HtmlTableCell HTCell3 = new HtmlTableCell();
            TextBox txtSaleReturnSR = new TextBox();
            txtSaleReturnSR.ID = "txtSaleReturnSR" + RowCount.ToString();
            txtSaleReturnSR.CssClass = "DisableInputNumber";
            txtSaleReturnSR.Width = Unit.Percentage(98);
            txtSaleReturnSR.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
            HiddenField hidSaleReturnAmtSR = new HiddenField();
            hidSaleReturnAmtSR.ID = "hidSaleReturnAmtSR" + RowCount.ToString();
            HTCell3.Controls.Add(txtSaleReturnSR);
            HTCell3.Controls.Add(hidSaleReturnAmtSR);
            LstSaleReturnSR.Add(txtSaleReturnSR.ID);
            LstSaleReturnAmtSR.Add(hidSaleReturnAmtSR.ID);

            HtmlTableCell HTCell4 = new HtmlTableCell();
            TextBox txtTotalAmtSR = new TextBox();
            txtTotalAmtSR.ID = "txtTotalAmtSR" + RowCount.ToString();
            txtTotalAmtSR.CssClass = "DisableInputNumber";
            txtTotalAmtSR.Width = Unit.Percentage(98);
            txtTotalAmtSR.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
            HTCell4.Controls.Add(txtTotalAmtSR);
            LstTotalAmtSR.Add(txtTotalAmtSR.ID);

            HTRow.Cells.Add(HTCell0);
            HTRow.Cells.Add(HTCell1);
            HTRow.Cells.Add(HTCell2);
            HTRow.Cells.Add(HTCell3);
            HTRow.Cells.Add(HTCell4);
            tblTDSSaleReturn.Rows.Add(HTRow);

            hidRowCountSR.Value = RowCount.ToString();

            ViewState["LstChkDeleteSR"] = LstChkDeleteSR;
            ViewState["LstCountSR"] = LstCountSR;
            ViewState["LstParticularSR"] = LstParticularSR;
            ViewState["LstServiceSR"] = LstServiceSR;
            ViewState["LstSaleReturnSR"] = LstSaleReturnSR;
            ViewState["LstSaleReturnAmtSR"] = LstSaleReturnAmtSR;
            ViewState["LstTotalAmtSR"] = LstTotalAmtSR;
        }
    }
    private void _Override_tblTDSSaleReturn()
    {
        LstCountSR = (List<string>)ViewState["LstCountSR"];
        LstParticularSR = (List<string>)ViewState["LstParticularSR"];
        LstServiceSR = (List<string>)ViewState["LstServiceSR"];
        LstSaleReturnSR = (List<string>)ViewState["LstSaleReturnSR"];
        LstSaleReturnAmtSR = (List<string>)ViewState["LstSaleReturnAmtSR"];
        LstTotalAmtSR = (List<string>)ViewState["LstTotalAmtSR"];
        LstChkDeleteSR = (List<string>)ViewState["LstChkDeleteSR"];

        if (LstCountSR != null)
        {
            int Count = Convert.ToInt32(LstCountSR.Count);
            for (int i = 0; i < Count; i++)
            {
                HtmlTableRow HTRow = new HtmlTableRow();

                HtmlTableCell HTCell0 = new HtmlTableCell();
                HTCell0.Align = "Center";
                CheckBox chkDeleteSR = new CheckBox();
                chkDeleteSR.ID = LstChkDeleteSR[i].ToString();
                chkDeleteSR.Width = Unit.Percentage(98);
                chkDeleteSR.Enabled = false;
               // chkDeleteSR.Attributes.Add("onclick", "checkAlLChecked();");
                HTCell0.Controls.Add(chkDeleteSR);

                HtmlTableCell HTCell1 = new HtmlTableCell();
                TextBox txtParticularSR = new TextBox();
                txtParticularSR.ID = LstParticularSR[i].ToString();
                txtParticularSR.CssClass = "DisableInput";
                txtParticularSR.Width = Unit.Percentage(98);
                txtParticularSR.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
                HTCell1.Controls.Add(txtParticularSR);

                HtmlTableCell HTCell2 = new HtmlTableCell();
                TextBox txtServiceSR = new TextBox();
                txtServiceSR.ID = LstServiceSR[i].ToString();
                txtServiceSR.CssClass = "DisableInput";
                txtServiceSR.Width = Unit.Percentage(98);
                txtServiceSR.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
                HTCell2.Controls.Add(txtServiceSR);

                HtmlTableCell HTCell3 = new HtmlTableCell();
                TextBox txtSaleReturnSR = new TextBox();
                txtSaleReturnSR.ID = LstSaleReturnSR[i].ToString();
                txtSaleReturnSR.CssClass = "DisableInputNumber";
                txtSaleReturnSR.Width = Unit.Percentage(98);
                txtSaleReturnSR.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
                HiddenField hidSaleReturnAmtSR = new HiddenField();
                hidSaleReturnAmtSR.ID = LstSaleReturnAmtSR[i].ToString();
                HTCell3.Controls.Add(txtSaleReturnSR);
                HTCell3.Controls.Add(hidSaleReturnAmtSR);

                HtmlTableCell HTCell4 = new HtmlTableCell();
                TextBox txtTotalAmtSR = new TextBox();
                txtTotalAmtSR.ID = LstTotalAmtSR[i].ToString();
                txtTotalAmtSR.CssClass = "DisableInputNumber";
                txtTotalAmtSR.Width = Unit.Percentage(98);
                txtTotalAmtSR.Attributes.Add("onkeydown", "return EnabledTabKey(this.id, event);");
                HTCell4.Controls.Add(txtTotalAmtSR);

                HTRow.Cells.Add(HTCell0);
                HTRow.Cells.Add(HTCell1);
                HTRow.Cells.Add(HTCell2);
                HTRow.Cells.Add(HTCell3);
                HTRow.Cells.Add(HTCell4);
                tblTDSSaleReturn.Rows.Add(HTRow);
            }
        }
    }
    private void _ResetTables()
    {
        _DeleteAllRow_MainTable();
        _DeleteAllRow_Details();
        _GetParticular_MainTable(ddlInvoiceParticular1);
        txtAddDescription1.Text = "";
        txtOriginalAmt1.Text = "";
        txtPendingAmt1.Text = "";
        txtTotalAmount1.Text = "";
        ddlServices1.Items.Clear();
        txtTaxableAmt.Text = "";
        txtNonTaxableAmt.Text = "";
        txtPECessAmt.Text = "";
        txtHECessAmt.Text = "";
        txtServiceTaxAmt.Text = "";
        txtTotalAmount.Text = "";
    }
    private string _GetRembursmentService(string strServiceId)
    {
        string strTaxability = "1";
        strsql = "Select TAXABILITY From IVC_ServiceMaster where SERVICEID='" + strServiceId + "'";
        DataTable DT = DU.getdata(strsql);
        if (DT.Rows.Count > 0)
        {
            if (DT.Rows[0]["TAXABILITY"].ToString() == "2")
            {

                strTaxability = "0";
            }
            else
            {
                strTaxability = "1";
            }
        }
        return strTaxability;
    }
    private void _DeleteZeroValueItemInDropdownlist(DropDownList ddl)
    {
        if (ddl.Items.Count > 0)
        {
            for (int i = 0; i < ddl.Items.Count; i++)
            {
                if (ddl.Items[i].Value == "0")
                {
                    ddl.Items.RemoveAt(i);
                    break;
                }
            }
        }
    }
    protected void ddlCustomer_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        _ResetTables();
        //display.DataSource = _ReturnParticular();
        //display.DataBind();
        //GridView1.DataSource = _ReturnPendingService_Details();
        //GridView1.DataBind();
    }
    protected void ddlFormat_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        string strFinyear = Session["FINYEAR"].ToString();
        if (strFinyear != string.Empty)
        {
            SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@TFOID",ddlFormat.SelectedValue),
                                        new SqlParameter("@FINYEAR",strFinyear)
                                    };
            DataTable DTVoucher = DU.getdatausingprocedure("USP_IVC_GetMaxVoucherNo", sparam);
            if (DTVoucher.Rows.Count > 0)
            {
                txtPrefix.Text = DTVoucher.Rows[0]["prefix"].ToString();
                txtCreditNoteNo.Text = DTVoucher.Rows[0]["vouno"].ToString();
                txtSuffix.Text = DTVoucher.Rows[0]["suffix"].ToString();
            }
            else
            {
                txtPrefix.Text = "";
                txtCreditNoteNo.Text = "";
                txtSuffix.Text = "";
            }
        }
        _BindEditTranFormat_HeadOfAccounts(ddlFormat.SelectedValue);
        _EnableDisableControls(ddlFormat.SelectedValue);
    }
    private void _BindEditTranFormat_HeadOfAccounts(string strFormatId)
    {
        if (strFormatId != string.Empty)
        {
            SqlParameter[] sparam ={
                                       new SqlParameter("@FORMATID",strFormatId)
                                   };
            DataTable DTFormatHead = DU.getdatausingprocedure("USP_IVC_GetTransactionFormat_HeadOfAccounts", sparam);
            if (DTFormatHead.Rows.Count > 0)
            {
                hidTDSLid.Value = DTFormatHead.Rows[0]["TDS_LEDGERID"].ToString();
                hidWriteOffLid.Value = DTFormatHead.Rows[0]["WRITEOFF_LEDGERID"].ToString();
            }
        }
    }
    protected void rbtCreditNoteType_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        _ResetTables();
        chkDelete1.Checked = false;
        if (rbtCreditNoteType.SelectedValue == "0")
        {
            panelCreditNote.Visible = true;
            panelSalesReturn.Visible = false;
          
        }
        else if (rbtCreditNoteType.SelectedValue == "1")
        {
            panelCreditNote.Visible = false;
            panelSalesReturn.Visible = true;
          
        }

    }
    protected void txtDate_OnTextChanged(object sender, EventArgs e)
    {
        _GetCurrentServiceTaxRate(txtDate.Text.ToString());
    }
    protected void btnAddMore_CLick(object sender, EventArgs e)
    {
        _AddMoreRow_MainTable();
    }
    protected void btnDeleteRow_Click(object sender, EventArgs e)
    {
        _DeleteAllRow_MainTable();
    }
    protected void ddlParticular_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
     
        int rowIndex = Convert.ToInt32(ddl.ID.ToString().Substring(20));
        DataTable DTParticular = _ReturnParticular();
        DataTable DTService = _ReturnPendingService_Details();
        DropDownList ddl1 = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlInvoiceParticular" + rowIndex);
        string selectedvalDDL = ddl1.SelectedValue.ToString();
        DropDownList ddlServices = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlServices" + rowIndex);
        TextBox txtOriginalAmt = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtOriginalAmt" + rowIndex);
        TextBox txtPendingAmt = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtPendingAmt" + rowIndex);
        TextBox txtTotalAmount = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtTotalAmount" + rowIndex);
        HiddenField hidServiceTaxRate = (HiddenField)tblCreditNoteMain.Rows[rowIndex].FindControl("hidServiceTaxRate" + rowIndex);
        HiddenField hidPECessRate = (HiddenField)tblCreditNoteMain.Rows[rowIndex].FindControl("hidPECessRate" + rowIndex);
        HiddenField hidHECessRate = (HiddenField)tblCreditNoteMain.Rows[rowIndex].FindControl("hidHECessRate" + rowIndex);
       // Response.Write("DDL Items count=" + ddl.Items.Count);
    
      _GetParticular_MainTable(ddl);
     _DeleteZeroValueItemInDropdownlist(ddl);
     if (selectedvalDDL != "0")
     {
         ddl.SelectedValue = selectedvalDDL;
     }
        if (ddl.SelectedValue != "0")
        {
            DataView DVParticular = DTParticular.DefaultView;
            string strExpre ="ReferenceId = " + ddl.SelectedValue;
             //Response.Write(strExpre);
           DVParticular.RowFilter = strExpre;
            DataTable DTTempParticular = DVParticular.ToTable();

            string[] strOriginal = DTTempParticular.Rows[0]["OriginalAmount1"].ToString().Split(' ');
            txtOriginalAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(strOriginal[0])) + " " + strOriginal[1];

            string[] strPending = DTTempParticular.Rows[0]["PendingAmount1"].ToString().Split(' ');
            txtPendingAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(strPending[0])) + " " + strPending[1];

            DataTable DTServiceTaxRate = _GetBilledServiceTaxRate(DTTempParticular.Rows[0]["TransactionID"].ToString());
            if (DTServiceTaxRate.Rows.Count > 0)
            {
                hidServiceTaxRate.Value = DTServiceTaxRate.Rows[0]["SERVICETAXRATE"].ToString();
                hidPECessRate.Value = DTServiceTaxRate.Rows[0]["EDUCESS1RATE"].ToString();
                hidHECessRate.Value = DTServiceTaxRate.Rows[0]["EDUCESS2RATE"].ToString();
            }
            else
            {
                hidServiceTaxRate.Value = "0";
                hidPECessRate.Value = "0";
                hidHECessRate.Value = "0";
            }
            txtTotalAmount.Text = "";
            DataView DVService = DTService.DefaultView;
            DVService.RowFilter = "ReferenceSerial=" + ddl.SelectedValue;
            DataTable DTTempService = DVService.ToTable();
            if (DTTempService.Rows.Count > 0)
            {
                ddlServices.DataSource = DTTempService;
                ddlServices.DataTextField = "ServiceName";
                ddlServices.DataValueField = "ServiceId";
                ddlServices.DataBind();
                ddlServices.Items.Insert(0, new ListItem("", "0"));
            }
            else
            {
                ddlServices.Items.Clear();
                ddlServices.Items.Insert(0, new ListItem("", "0"));
            }
        }
        else
        {
            ddlServices.Items.Clear();
            ddlServices.Items.Insert(0, new ListItem("", "0"));
        }
    }
    protected void ddlServiecs_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        int rowIndex = Convert.ToInt32(ddl.ID.ToString().Substring(11));
        DataTable DTService = _ReturnPendingService_Details();
        DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlInvoiceParticular" + rowIndex);
        TextBox txtOriginalAmt = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtOriginalAmt" + rowIndex);
        TextBox txtPendingAmt = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtPendingAmt" + rowIndex);
        TextBox txtTotalAmount = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtTotalAmount" + rowIndex);
        HiddenField hidTotalAmout = (HiddenField)tblCreditNoteMain.Rows[rowIndex].FindControl("hidTotalAmout" + rowIndex);
        HiddenField hidServiceTaxability = (HiddenField)tblCreditNoteMain.Rows[rowIndex].FindControl("hidServiceTaxability" + rowIndex);
      //  _DeleteZeroValueItemInDropdownlist(ddl);
        if (ddl.SelectedValue != "0")
        {
            DataView DVService = new DataView();
            DVService = DTService.DefaultView;
            //Response.Write("ReferenceSerial='" + ddlInvoiceParticular.SelectedValue + "' and ServiceId='" + ddl.SelectedValue + "'");
            DVService.RowFilter = "ReferenceSerial='" + ddlInvoiceParticular.SelectedValue + "' and ServiceId='" + ddl.SelectedValue + "'";
            DataTable DTTempService = DVService.ToTable();
            if (DTTempService.Rows.Count > 0)
            {
                txtOriginalAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["Amount"].ToString()));
                txtPendingAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["PendingAmount"].ToString()));
                txtTotalAmount.Text = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["PendingAmount"].ToString()));
                hidTotalAmout.Value = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["PendingAmount"].ToString()));
                hidServiceTaxability.Value = _GetRembursmentService(ddl.SelectedValue);
                if (rbtCreditNoteType.SelectedValue == "0")
                {
                    _AddRow_tblCreditNote(rowIndex);
                    _BindDetails_tblTDSCreditNote(rowIndex);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "CalculateTotalCreditNoteAmt();", true);
                }
                else if (rbtCreditNoteType.SelectedValue == "1")
                {
                    _AddRow_tblTDSSaleReturn(rowIndex);
                    _BindDetails_tblTDSSaleReturn(rowIndex);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "CalculateTotalSaleReturnAmt();", true);
                }
            }
        }
        else
        {
            txtOriginalAmt.Text = "";
            txtPendingAmt.Text = "";
            txtTotalAmount.Text = "";
            hidServiceTaxability.Value = "1";
        }
    }
    private string _GetServiceLedgerId(string strServiceId)
    {
        string strLedgerId = string.Empty;
        if (strServiceId != string.Empty)
        {
            strsql = "SELECT LEDGERID FROM IVC_SERVICEMASTER WHERE SERVICEID='" + strServiceId + "'";
            DataTable DTLedger = DU.getdata(strsql);
            if (DTLedger.Rows.Count > 0)
            {
                strLedgerId = DTLedger.Rows[0]["LEDGERID"].ToString();
            }
        }
        return strLedgerId;
    }
    //private void _ResetControl(Control ctrl)
    //{
    //    foreach (Control c in ctrl.Controls)
    //    {
    //        if (c.GetType() == typeof(TextBox))
    //        {
    //            ((TextBox)(c)).Text = string.Empty;
    //        }
    //        if (c.GetType() == typeof(DropDownList))
    //        {
    //            ((DropDownList)(c)).SelectedValue = "0";
    //        }
    //        if (c.HasControls())
    //        {
    //            _ResetControl(c);
    //        }
    //    }
    //}
    private void _EnableDisableControls(string strFormatId)
    {
        if (strFormatId != string.Empty)
        {
            SqlParameter[] sparam ={
                                   new  SqlParameter("@FORMATID",strFormatId)
                               };
            DataTable DTFormat = DU.getdatausingprocedure("USP_IVC_GetTransactionFormat", sparam);
            if (DTFormat.Rows.Count > 0)
            {
                if (Convert.ToBoolean(DTFormat.Rows[0]["NARRATION"]) == true)
                {
                    txtNarration.Text = "";
                    txtNarration.Enabled = true;
                }
                else
                {
                    txtNarration.Text = "";
                    txtNarration.Enabled = false;
                }
                if (Convert.ToBoolean(DTFormat.Rows[0]["REMARKS"]) == true)
                {
                    txtRemarks.Text = "";
                    txtRemarks.Enabled = true;
                }
                else
                {
                    txtRemarks.Text = "";
                    txtRemarks.Enabled = false;
                }
                if (Convert.ToBoolean(DTFormat.Rows[0]["PREPAREDBY"]) == true)
                {
                    txtPreparedBy.Text = "";
                    txtPreparedBy.Enabled = true;
                }
                else
                {
                    txtPreparedBy.Text = "";
                    txtPreparedBy.Enabled = false;
                }
                if (Convert.ToBoolean(DTFormat.Rows[0]["CHECKEDBY"]) == true)
                {
                    txtCheckedBy.Text = "";
                    txtCheckedBy.Enabled = true;
                }
                else
                {
                    txtCheckedBy.Text = "";
                    txtCheckedBy.Enabled = false;
                }
            }
        }
    }
  
    private string _SaveVouchers()
    {
        try
        {
            string strTranDate = string.Empty;
            string strTranTypeId = string.Empty;
            if (txtDate.Text != string.Empty)
            {
                string[] strTemp = txtDate.Text.Split('/');
                strTranDate = strTemp[1] + "/" + strTemp[0] + "/" + strTemp[2];
            }
            SqlParameter[] sparam ={
                                    new SqlParameter("@PARENTTYPEID","2"),
                                    new SqlParameter("@BILLFORMATID",ddlFormat.SelectedValue),
                                    new SqlParameter("@MODULETYPE","3")
                                };
            DataTable DTTranTypeId = DU.getdatausingprocedure("USP_ACC_GetTransactionSettingBasedOnFormat", sparam);
            if (DTTranTypeId.Rows.Count > 0)
            {
                strTranTypeId = DTTranTypeId.Rows[0]["TypeID"].ToString();
            }
            if (strTranTypeId != string.Empty)
            {
                SqlParameter[] sparam1 = 
                                {
                                    new SqlParameter("@TransactionId",hidTranID.Value.ToString()),
                                    new SqlParameter("@TransactionTypeID",strTranTypeId),      
                                    new SqlParameter("@TransactionNumber",txtCreditNoteNo.Text),      
                                    new SqlParameter("@FinYear",Session["FINYEAR"].ToString()),      
                                    new SqlParameter("@ReferenceNumber",txtRefNo.Text),     
                                    new SqlParameter("@IsCashVoucher","0"),      
                                    new SqlParameter("@TransactionDate",strTranDate),      
                                    new SqlParameter("@Narration",txtNarration.Text),     
                                    new SqlParameter("@CreditDays","0"),         
                                    new SqlParameter("@ModifiedBy",Session["userid"].ToString()),      
                                    new SqlParameter("@IsCancelled","0"),      
                                    new SqlParameter("@CostCentreClassID","0")  
                                };
                int Result = DU.executeprocedure("USP_ACC_UpdateTransaction", sparam1);
                if (Result > 0)
                {
                        _SaveVouchers_Details(hidTranID.Value.ToString());
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text += ex.Message;
            throw ex;
        }
        return hidTranID.Value.ToString();
    }
    private void _SaveVouchers_Details(string strTranId)
    {
        try
        {
            if (strTranId != string.Empty)
            {
                //string strsql = "Delete from ACC_VOUDETAILS where TRANID=" + hidTranID.Value.ToString() + " and RECDATE='" + string.Format("{0:MM/dd/yyyy}", Convert.ToDateTime(hidVoudate.Value.ToString())) + "'";
                //DataTable dtFromVouDetails = DU.getdata(strsql);

                string strTranDate = string.Empty;
                if (txtDate.Text != string.Empty)
                {
                    string[] strTemp = txtDate.Text.Split('/');
                    strTranDate = strTemp[1] + "/" + strTemp[0] + "/" + strTemp[2];
                }
                if (ddlCustomer.SelectedValue != "0")
                {
                    string strCreditNoteId = _SaveCreditNote_Main(strTranId);
                    SqlParameter[] sparam =
                                                {
                                                    new SqlParameter("@TransactionId",strTranId),
                                                    new SqlParameter("@LedgerId",ddlCustomer.SelectedValue),
                                                    new SqlParameter("@Amount",txtTotalAmount.Text),
                                                    new SqlParameter("@IsReconciled","0"),
                                                    new SqlParameter("@ReconciledDate",strTranDate)
                                                };
                    int Result = DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                    if (Result > 0)
                    {
                        strsql = "Select Ident_Current('ACC_VOUDETAILS') as VouSerial";
                        DataTable DT = DU.getdata(strsql);
                        if (DT.Rows.Count > 0)
                        {
                            _SaveReference_Details( strCreditNoteId,DT.Rows[0]["VouSerial"].ToString());
                        }
                    }
                }
                if (rbtCreditNoteType.SelectedValue == "0")
                {
                    int count = Convert.ToInt32(hidRowCountCN.Value);
                    double tdsAmount = 0;
                    double WriteOffAmount = 0;
                    for (int i = 1; i <= count; i++)
                    {
                        DropDownList ddlServices = (DropDownList)tblCreditNoteMain.Rows[i].FindControl("ddlServices" + i.ToString());
                        TextBox txtTDSAmtCN = (TextBox)tblTdsCreditNote.Rows[i].FindControl("txtTDSAmtCN" + i.ToString());
                        HiddenField hidDiscountAmtCN = (HiddenField)tblTdsCreditNote.Rows[i].FindControl("hidDiscountAmtCN" + i.ToString());
                        HiddenField hidWriteOffAmtCN = (HiddenField)tblTdsCreditNote.Rows[i].FindControl("hidWriteOffAmtCN" + i.ToString());
                        if (ddlServices.SelectedValue != "0")
                        {
                            string strServiceLid = _GetServiceLedgerId(ddlServices.SelectedValue);
                            if (hidDiscountAmtCN.Value != string.Empty && Convert.ToDouble(hidDiscountAmtCN.Value) > 0 && strServiceLid != string.Empty)
                            {
                                double amount = 0 - Convert.ToDouble(hidDiscountAmtCN.Value);
                                SqlParameter[] sparam =
                                            {
                                                new SqlParameter("@TransactionId",strTranId),
                                                new SqlParameter("@LedgerId",strServiceLid),
                                                new SqlParameter("@Amount",amount),
                                                new SqlParameter("@IsReconciled","0"),
                                                new SqlParameter("@ReconciledDate",strTranDate)
                                            };
                                DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                            }
                        }
                        if (txtTDSAmtCN.Text != string.Empty && Convert.ToDouble(txtTDSAmtCN.Text.Trim()) > 0)
                        {
                            tdsAmount += Convert.ToDouble(txtTDSAmtCN.Text.Trim());
                        }
                        if (hidWriteOffAmtCN.Value != string.Empty && Convert.ToDouble(hidWriteOffAmtCN.Value) > 0)
                        {
                            WriteOffAmount += Convert.ToDouble(hidWriteOffAmtCN.Value);
                        }
                    }
                    if (tdsAmount > 0)
                    {
                        double amount = 0 - tdsAmount;
                        SqlParameter[] sparam =
                                            {
                                                new SqlParameter("@TransactionId",strTranId),
                                                new SqlParameter("@LedgerId",hidTDSLid.Value),
                                                new SqlParameter("@Amount",amount),
                                                new SqlParameter("@IsReconciled","0"),
                                                new SqlParameter("@ReconciledDate",strTranDate)
                                            };
                        DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                    }
                    if (WriteOffAmount > 0)
                    {
                        double amount = 0 - WriteOffAmount;
                        SqlParameter[] sparam =
                                            {
                                                new SqlParameter("@TransactionId",strTranId),
                                                new SqlParameter("@LedgerId",hidWriteOffLid.Value),
                                                new SqlParameter("@Amount",amount),
                                                new SqlParameter("@IsReconciled","0"),
                                                new SqlParameter("@ReconciledDate",strTranDate)
                                            };
                        DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                    }
                }
                else if (rbtCreditNoteType.SelectedValue == "1")
                {
                    int count = Convert.ToInt32(hidRowCountSR.Value);
                    for (int i = 1; i <= count; i++)
                    {
                        DropDownList ddlServices = (DropDownList)tblCreditNoteMain.Rows[i].FindControl("ddlServices" + i.ToString());
                        TextBox txtTotalAmtSR = (TextBox)tblTDSSaleReturn.Rows[i].FindControl("txtTotalAmtSR" + i.ToString());
                        if (ddlServices.SelectedValue != "0")
                        {
                            string strServiceLid = _GetServiceLedgerId(ddlServices.SelectedValue);
                            if (txtTotalAmtSR.Text != string.Empty && Convert.ToDouble(txtTotalAmtSR.Text) > 0 && strServiceLid != string.Empty)
                            {
                                double amount = 0 - Convert.ToDouble(txtTotalAmtSR.Text.Trim());
                                SqlParameter[] sparam =
                                            {
                                                new SqlParameter("@TransactionId",strTranId),
                                                new SqlParameter("@LedgerId",strServiceLid),
                                                new SqlParameter("@Amount",amount),
                                                new SqlParameter("@IsReconciled","0"),
                                                new SqlParameter("@ReconciledDate",strTranDate)
                                            };
                                DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                            }
                        }
                    }
                }
                if (txtServiceTaxAmt.Text != string.Empty && Convert.ToDouble(txtServiceTaxAmt.Text) > 0 && hidServiceTaxLid.Value != string.Empty)
                {
                    double amount = 0 - Convert.ToDouble(txtServiceTaxAmt.Text.Trim());
                    SqlParameter[] sparam =
                                            {
                                                new SqlParameter("@TransactionId",strTranId),
                                                new SqlParameter("@LedgerId",hidServiceTaxLid.Value),
                                                new SqlParameter("@Amount",amount),
                                                new SqlParameter("@IsReconciled","0"),
                                                new SqlParameter("@ReconciledDate",strTranDate)
                                            };
                    DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);

                }
                if (txtPECessAmt.Text != string.Empty && Convert.ToDouble(txtPECessAmt.Text) > 0 && hidPECessLid.Value != string.Empty)
                {
                    double amount = 0 - Convert.ToDouble(txtPECessAmt.Text.Trim());
                    SqlParameter[] sparam =
                                            {
                                                new SqlParameter("@TransactionId",strTranId),
                                                new SqlParameter("@LedgerId",hidPECessLid.Value),
                                                new SqlParameter("@Amount",amount),
                                                new SqlParameter("@IsReconciled","0"),
                                                new SqlParameter("@ReconciledDate",strTranDate)
                                            };
                    DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);

                }
                if (txtHECessAmt.Text != string.Empty && Convert.ToDouble(txtHECessAmt.Text) > 0 && hidHECessLid.Value != string.Empty)
                {
                    double amount = 0 - Convert.ToDouble(txtHECessAmt.Text.Trim());
                    SqlParameter[] sparam =
                                                {
                                                    new SqlParameter("@TransactionId",strTranId),
                                                    new SqlParameter("@LedgerId",hidHECessLid.Value),
                                                    new SqlParameter("@Amount",amount),
                                                    new SqlParameter("@IsReconciled","0"),
                                                    new SqlParameter("@ReconciledDate",strTranDate)
                                                };
                    DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);

                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text += ex.Message;
            throw ex;
        }
    }
    private void _SaveReference_Details(string strCreditNoteId, string strVouSerial)
    {
        try
        {
            if (strCreditNoteId != string.Empty)
            {
                string strChildID = string.Empty;
                string strRefID = string.Empty;
                string strRefDate = string.Empty;
                string strRefferenceNo = string.Empty;
                if (txtDate.Text.ToString() != string.Empty)
                {
                    string[] str = txtDate.Text.ToString().Split('/');
                    strRefDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
                }

                int OldCount = Convert.ToInt32(hidOldChildIDCount.Value.ToString());
                int NewCount = Convert.ToInt32(hidRowCountMain.Value);
                if (NewCount > OldCount)
                {
                    for (int i = 1; i <= NewCount; i++)
                    {
                        CheckBox chkDelete = (CheckBox)tblCreditNoteMain.FindControl("chkDelete" + i.ToString());
                        if (i <= OldCount)
                        {
                            HiddenField hidChildID = (HiddenField)tblOldChildID.FindControl("hidOldChildID" + i.ToString());
                            HiddenField hidRefID = (HiddenField)tblOldChildID.FindControl("hidRefID" + i.ToString());

                            if (chkDelete.Checked == true)
                            {
                                strChildID += hidChildID.Value.ToString() + ",";
                                strRefID += hidRefID.Value.ToString() + ",";
                            }
                            else
                            {
                                DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[i].FindControl("ddlInvoiceParticular" + i);
                                TextBox txtCreditNoteAmt = (TextBox)tblCreditNoteMain.Rows[i].FindControl("txtTotalAmount" + i);
                                if (ddlInvoiceParticular.SelectedValue != "0" && txtCreditNoteAmt.Text != string.Empty)
                                {
                                    SqlParameter[] sparam = {
                                            new SqlParameter("@ReferenceSerial",hidRefID.Value.ToString()),
                                            new SqlParameter("@ParentReference",ddlInvoiceParticular.SelectedValue),
                                            new SqlParameter("@TransactionSerial",strVouSerial),
                                            new SqlParameter("@ReferenceType","2"),
                                            new SqlParameter("@Reference",ddlInvoiceParticular.SelectedItem.Text),
                                            new SqlParameter("@ReferenceDate",strRefDate),
                                            new SqlParameter("@CreditDays","0"),
                                            new SqlParameter("@ReferenceAmount",txtTotalAmount.Text.Trim()),
                                            new SqlParameter("@IsTDSDeducted","0")
                                };
                                    DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam);
                                }
                                _SaveCreditNote_Child("U", hidChildID.Value.ToString(), hidRefID.Value.ToString(), chkDelete.Checked, i);
                            }
                        }
                        else
                        {
                            if (chkDelete.Checked != true)
                            {
                                DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[i].FindControl("ddlInvoiceParticular" + i);
                                TextBox txtCreditNoteAmt = (TextBox)tblCreditNoteMain.Rows[i].FindControl("txtTotalAmount" + i);
                                if (ddlInvoiceParticular.SelectedValue != "0" && txtCreditNoteAmt.Text != string.Empty)
                                {
                                    SqlParameter[] sparam = {
                                            new SqlParameter("@ReferenceSerial","0"),
                                            new SqlParameter("@ParentReference",ddlInvoiceParticular.SelectedValue),
                                            new SqlParameter("@TransactionSerial",strVouSerial),
                                            new SqlParameter("@ReferenceType","2"),
                                            new SqlParameter("@Reference",ddlInvoiceParticular.SelectedItem.Text),
                                            new SqlParameter("@ReferenceDate",strRefDate),
                                            new SqlParameter("@CreditDays","0"),
                                            new SqlParameter("@ReferenceAmount",txtTotalAmount.Text.Trim()),
                                            new SqlParameter("@IsTDSDeducted","0")
                                                                };
                                    int result = DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam);
                                    if (result > 0)
                                    {
                                        strsql = "Select Ident_Current('ACC_REFDETAILS') as REFSERIAL";
                                        DataTable DTCrediteNote = DU.getdata(strsql);
                                        if (DTCrediteNote.Rows.Count > 0)
                                        {
                                            _SaveCreditNote_Child("U", "0", DTCrediteNote.Rows[0]["REFSERIAL"].ToString(), chkDelete.Checked, i);
                                        }
                                    }
                                }
                            }
                        }
                        if (strChildID != string.Empty)
                        {
                            string[] strChild = strChildID.Split(',');
                            string[] strRef = strRefID.Split(',');
                            for (int f = 0; f <= strChild.Length; f++)
                            {
                                if (chkDelete.Checked != true)
                                {
                                    string strp = strChild[f].ToString();
                                    string strRf = strRef[f].ToString();
                                    if (strp != string.Empty)
                                    {
                                        DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[i].FindControl("ddlInvoiceParticular" + i);
                                        TextBox txtCreditNoteAmt = (TextBox)tblCreditNoteMain.Rows[i].FindControl("txtTotalAmount" + i);
                                        if (ddlInvoiceParticular.SelectedValue != "0" && txtCreditNoteAmt.Text != string.Empty)
                                        {
                                            SqlParameter[] sparam = {
                                            new SqlParameter("@ReferenceSerial",strRef),
                                            new SqlParameter("@ParentReference",ddlInvoiceParticular.SelectedValue),
                                            new SqlParameter("@TransactionSerial",strVouSerial),
                                            new SqlParameter("@ReferenceType","2"),
                                            new SqlParameter("@Reference",ddlInvoiceParticular.SelectedItem.Text),
                                            new SqlParameter("@ReferenceDate",strRefDate),
                                            new SqlParameter("@CreditDays","0"),
                                            new SqlParameter("@ReferenceAmount",txtTotalAmount.Text.Trim()),
                                            new SqlParameter("@IsTDSDeducted","0")
                                                                };
                                            DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam);
                                        }
                                        _SaveCreditNote_Child(Convert.ToString("U"), strp.ToString(),strRef.ToString(), chkDelete.Checked, i);
                                    }
                                }
                            }
                        }
                        //else
                        //{
                            //if (chkDelete.Checked != true)
                            //{
                            //    DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[i].FindControl("ddlInvoiceParticular" + i);
                            //    TextBox txtCreditNoteAmt = (TextBox)tblCreditNoteMain.Rows[i].FindControl("txtTotalAmount" + i);
                            //    if (ddlInvoiceParticular.SelectedValue != "0" && txtCreditNoteAmt.Text != string.Empty)
                            //    {
                            //        SqlParameter[] sparam = {
                            //                new SqlParameter("@ReferenceSerial","0"),
                            //                new SqlParameter("@ParentReference",ddlInvoiceParticular.SelectedValue),
                            //                new SqlParameter("@TransactionSerial",strVouSerial),
                            //                new SqlParameter("@ReferenceType","2"),
                            //                new SqlParameter("@Reference",ddlInvoiceParticular.SelectedItem.Text),
                            //                new SqlParameter("@ReferenceDate",strRefDate),
                            //                new SqlParameter("@CreditDays","0"),
                            //                new SqlParameter("@ReferenceAmount",txtTotalAmount.Text.Trim()),
                            //                new SqlParameter("@IsTDSDeducted","0")
                            //                                    };
                            //        int result = DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam);
                            //        if (result > 0)
                            //        {
                            //            strsql = "Select Ident_Current('ACC_REFDETAILS') as REFSERIAL";
                            //            DataTable DTCrediteNote = DU.getdata(strsql);
                            //            if (DTCrediteNote.Rows.Count > 0)
                            //            {
                            //                _SaveCreditNote_Child("U", "0", DTCrediteNote.Rows[0]["REFSERIAL"].ToString(), chkDelete.Checked, i);
                            //            }
                            //        }
                            //    }
                            //}
                        //}
                    }
                }
                else
                {
                    for (int i = 1; i <= NewCount; i++)
                    {
                        CheckBox chkDelete = (CheckBox)tblCreditNoteMain.FindControl("chkDelete" + i.ToString());
                        HiddenField hidChildID = (HiddenField)tblOldChildID.FindControl("hidOldChildID" + i.ToString());
                        HiddenField hidRefID = (HiddenField)tblOldChildID.FindControl("hidRefID" + i.ToString());

                        if (chkDelete.Checked == true)
                        {
                            string strsql = "Delete from ACC_REFDETAILS where Refserial=" + hidRefID.Value.ToString();
                            DU.executesql(strsql);
                            _SaveCreditNote_Child("D", hidChildID.Value.ToString(),hidRefID.Value.ToString(),chkDelete.Checked, i);
                        }
                        else
                        {
                            DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[i].FindControl("ddlInvoiceParticular" + i);
                            TextBox txtCreditNoteAmt = (TextBox)tblCreditNoteMain.Rows[i].FindControl("txtTotalAmount" + i);
                            if (ddlInvoiceParticular.SelectedValue != "0" && txtCreditNoteAmt.Text != string.Empty)
                            {
                                SqlParameter[] sparam = {
                                            new SqlParameter("@ReferenceSerial",hidRefID.Value.ToString()),
                                            new SqlParameter("@ParentReference",ddlInvoiceParticular.SelectedValue),
                                            new SqlParameter("@TransactionSerial",strVouSerial),
                                            new SqlParameter("@ReferenceType","2"),
                                            new SqlParameter("@Reference",ddlInvoiceParticular.SelectedItem.Text),
                                            new SqlParameter("@ReferenceDate",strRefDate),
                                            new SqlParameter("@CreditDays","0"),
                                            new SqlParameter("@ReferenceAmount",txtTotalAmount.Text.Trim()),
                                            new SqlParameter("@IsTDSDeducted","0")
                                };
                                DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam);
                            }
                            _SaveCreditNote_Child("U",hidChildID.Value.ToString(), hidRefID.Value.ToString(), chkDelete.Checked, i);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text += ex.Message;
            throw ex;
        }
    }
    private string _SaveCreditNote_Main(string strTranId)
    {
        try
        {
            if (strTranId != string.Empty)
            {
                SqlParameter[] sparam ={
       
                                       new SqlParameter("@CREDITNOTEID",hidCreditNoteID.Value.ToString()),
                                       new SqlParameter("@TRANID",strTranId),
                                       new SqlParameter("@FORMATID",ddlFormat.SelectedValue),
                                       new SqlParameter("@CUSTOMERLEDGERID",ddlCustomer.SelectedValue),
                                       new SqlParameter("@REMARKS",txtRemarks.Text.Trim()),
                                       new SqlParameter("@CHECKEDBY",txtCheckedBy.Text.Trim()),
                                       new SqlParameter("@PREPAREDBY",txtPreparedBy.Text.Trim()),
                                       new SqlParameter("@ISTDSAPPLIED","0"),
                                       new SqlParameter("@ISSALESRETURN",rbtCreditNoteType.SelectedValue)
                                   };
                int result = DU.executeprocedure("USP_IVC_SaveCreditNote", sparam);
                if (result > 0)
                {
                    _SaveCreditNote_Total(hidCreditNoteID.Value.ToString());
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text += ex.Message;
            throw ex;
        }
        return hidCreditNoteID.Value.ToString();
    }
    private void _SaveCreditNote_Child(string status, string strCreditNoteChildId, string strRefId, bool ChkChecked, int rowIndex)
    {
        try
        {
            if (ChkChecked == true && status == "D")
            {
                if (strCreditNoteChildId != string.Empty && strCreditNoteChildId != "0")
                {
                    string strsql = "Delete from IVC_CREDITNOTE_CHILD where CREDITNOTECHILDID=" + strCreditNoteChildId;
                    DU.executesql(strsql);
                    _SaveCreditNote_TDS(status, strCreditNoteChildId, ChkChecked, rowIndex);
                }
            }
            else
            {
                DataTable DTParticular = _ReturnParticular();
                DataTable DTService = _ReturnPendingService_Details();

                DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlInvoiceParticular" + rowIndex);
                DropDownList ddlServices = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlServices" + rowIndex);
                TextBox txtTotalAmount = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtTotalAmount" + rowIndex);
                TextBox txtAddDescription = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtAddDescription" + rowIndex);

                DataView DVService = new DataView();
                DVService = DTService.DefaultView;
                DVService.RowFilter = "ReferenceSerial='" + ddlInvoiceParticular.SelectedValue + "' and ServiceId='" + ddlServices.SelectedValue + "'";
                DataTable DTTempService = DVService.ToTable();

                if (rbtCreditNoteType.SelectedValue == "0")
                {
                    TextBox txtTDSAmtCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtTDSAmtCN" + rowIndex);
                    TextBox txtDiscountCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtDiscountCN" + rowIndex);
                    TextBox txtWriteOffCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtWriteOffCN" + rowIndex);
                    HiddenField hidDiscountAmtCN = (HiddenField)tblTdsCreditNote.Rows[rowIndex].FindControl("hidDiscountAmtCN" + rowIndex);
                    HiddenField hidWriteOffAmtCN = (HiddenField)tblTdsCreditNote.Rows[rowIndex].FindControl("hidWriteOffAmtCN" + rowIndex);
                    if (txtTDSAmtCN.Text == string.Empty)
                    {
                        txtTDSAmtCN.Text = "0";
                    }
                    if (txtDiscountCN.Text == string.Empty)
                    {
                        txtDiscountCN.Text = "0";
                    }
                    if (txtWriteOffCN.Text == string.Empty)
                    {
                        txtWriteOffCN.Text = "0";
                    }
                    if (hidDiscountAmtCN.Value == string.Empty)
                    {
                        hidDiscountAmtCN.Value = "0";
                    }
                    if (hidWriteOffAmtCN.Value == string.Empty)
                    {
                        hidWriteOffAmtCN.Value = "0";
                    }

                    if (DTTempService.Rows.Count > 0)
                    {
                        SqlParameter[] sparam ={
                                       new SqlParameter("@CREDITNOTECHILDID",strCreditNoteChildId),
                                       new SqlParameter("@CREDITNOTEID",hidCreditNoteID.Value.ToString()),
                                       new SqlParameter("@REFERENCETRANID",DTTempService.Rows[0]["TRANID"].ToString()),
                                       new SqlParameter("@REFERENCECHILDID",DTTempService.Rows[0]["CHILDID"].ToString()),
                                       new SqlParameter("@REFERENCEID",strRefId),
                                       new SqlParameter("@SERVICEID",ddlServices.SelectedValue),
                                       new SqlParameter("@ADDDESC",txtAddDescription.Text.Trim()),
                                       new SqlParameter("@TDSAMOUNT",txtTDSAmtCN.Text),
                                       new SqlParameter("@WRITEOFFAMT",txtWriteOffCN.Text.Trim()),
                                       new SqlParameter("@WRITEOFFTAXABLEAMT",hidWriteOffAmtCN.Value),
                                       //new SqlParameter("@WRITEOFFABATEMENTAMT",""),
                                       //new SqlParameter("@WRITEOFFSERVICECHARGEAMT",""),
                                       new SqlParameter("@DISCOUNTAMT",txtDiscountCN.Text.Trim()),
                                       new SqlParameter("@DISCOUNTTAXABLEAMT",hidDiscountAmtCN.Value),
                                       //new SqlParameter("@DISCOUNTABATEMENTAMT",txtCheckedBy.Text.Trim()),
                                       //new SqlParameter("@DISCOUNTSERVICECHARGEAMT",txtPreparedBy.Text.Trim()),
                                       new SqlParameter("@AMOUNT",txtTotalAmount.Text)
                                   };
                        DU.executeprocedure("USP_IVC_SaveCreditNoteChildDetails", sparam);

                        if (strCreditNoteChildId == "0")
                        {
                            strsql = "Select Ident_Current('IVC_CREDITNOTE_CHILD') as CREDITNOTECHILDID";
                            DataTable DTCrediteNote = DU.getdata(strsql);
                            if (DTCrediteNote.Rows.Count > 0)
                            {
                                _SaveCreditNote_TDS(status, DTCrediteNote.Rows[0]["CREDITNOTECHILDID"].ToString(), ChkChecked, rowIndex);
                            }
                        }
                        else
                        {
                            _SaveCreditNote_TDS(status, strCreditNoteChildId, ChkChecked, rowIndex);
                        }
                    }
                }

                if (rbtCreditNoteType.SelectedValue == "1")
                {
                    HiddenField hidSaleReturnAmtSR = (HiddenField)tblTDSSaleReturn.Rows[rowIndex].FindControl("hidSaleReturnAmtSR" + rowIndex);
                    if (hidSaleReturnAmtSR.Value == string.Empty)
                    {
                        hidSaleReturnAmtSR.Value = "0";
                    }
                    if (DTTempService.Rows.Count > 0)
                    {
                        SqlParameter[] sparam ={
                                      new SqlParameter("@CREDITNOTECHILDID",strCreditNoteChildId),
                                       new SqlParameter("@CREDITNOTEID",hidCreditNoteID.Value.ToString()),
                                       new SqlParameter("@REFERENCETRANID",DTTempService.Rows[0]["TRANID"].ToString()),
                                       new SqlParameter("@REFERENCECHILDID",DTTempService.Rows[0]["CHILDID"].ToString()),
                                       new SqlParameter("@REFERENCEID",strRefId),
                                       new SqlParameter("@SERVICEID",ddlServices.SelectedValue),
                                       new SqlParameter("@ADDDESC",txtAddDescription.Text.Trim()),
                                       new SqlParameter("@TDSAMOUNT","0"),
                                       new SqlParameter("@WRITEOFFAMT","0"),
                                       //new SqlParameter("@WRITEOFFTAXABLEAMT",hidWriteOffAmtCN.Value),
                                       //new SqlParameter("@WRITEOFFABATEMENTAMT",""),
                                       //new SqlParameter("@WRITEOFFSERVICECHARGEAMT",""),
                                       new SqlParameter("@DISCOUNTAMT",txtTotalAmount.Text),
                                       new SqlParameter("@DISCOUNTTAXABLEAMT",hidSaleReturnAmtSR.Value),
                                       //new SqlParameter("@DISCOUNTABATEMENTAMT",txtCheckedBy.Text.Trim()),
                                       //new SqlParameter("@DISCOUNTSERVICECHARGEAMT",txtPreparedBy.Text.Trim()),
                                       new SqlParameter("@AMOUNT",txtTotalAmount.Text)
                                   };
                        DU.executeprocedure("USP_IVC_SaveCreditNoteChildDetails", sparam);
                    }
                        SqlParameter[] sparam1 ={
                                       new SqlParameter("@CREDITNOTECHILDID",strCreditNoteChildId),
                                       new SqlParameter("@CESS1RATE","0"),
                                       new SqlParameter("@CESS1AMT","0"),
                                       new SqlParameter("@CESS2RATE","0"),
                                       new SqlParameter("@CESS2AMT","0"),
                                       new SqlParameter("@SERVICERATE","0"),
                                       new SqlParameter("@SERVICEAMT","0"),
                                       new SqlParameter("@TDS","0"),
                                       new SqlParameter("@TDSTAXABLEAMT","0"),
                                       new SqlParameter("@ABATEMENTAMT","0"),
                                       new SqlParameter("@SERVICECHARGEAMT","0")
                                   };
                        DU.executeprocedure("USP_IVC_SaveCreditNoteTDSDetails", sparam1);
                    
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text += ex.Message;
            throw ex;
        }
    }
    private void _SaveCreditNote_Total(string strCreditNoteId)
    {
        try
        {
            if (strCreditNoteId != string.Empty)
            {
                SqlParameter[] sparam ={
                                       new  SqlParameter("@CREDITNOTEID",strCreditNoteId),
                                       new  SqlParameter("@TAXABLEAMT",txtTaxableAmt.Text.Trim()),
                                       new  SqlParameter("@NONTAXABLEAMT",txtNonTaxableAmt.Text.Trim()),
                                       new  SqlParameter("@SERVICETAXRATE",hidServiceTaxRateCurrent.Value),
                                       new  SqlParameter("@SERVICETAXAMT",txtServiceTaxAmt.Text.Trim()),
                                       new  SqlParameter("@EDUCESS1RATE",hidPECessRateCurrent.Value),
                                       new  SqlParameter("@EDUCESS1AMT",txtPECessAmt.Text.Trim()),
                                       new  SqlParameter("@EDUCESS2RATE",hidHECessRateCurrent.Value),
                                       new  SqlParameter("@EDUCESS2AMT",txtHECessAmt.Text.Trim()),
                                       new  SqlParameter("@TOTAL",txtTotalAmount.Text.Trim()),
                                       new  SqlParameter("@TDSAMOUNT",hidTotalTdsAmount.Value),
                                       new  SqlParameter("@WRITEOFFAMT",hidTotalWriteOffAmount.Value),
                                       new  SqlParameter("@DISCOUNTAMT",hidTotalDiscountAmount.Value),
                                       new  SqlParameter("@ADDITIONALTAXAMT",hidTotalAdditionalAmount.Value)
                                   };
                int Result = DU.executeprocedure("USP_IVC_SaveCreditNoteTotals", sparam);
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text += ex.Message;
            throw ex;
        }

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string str = string.Empty;
            using (TransactionScope scope = new TransactionScope())
            {
                //str = _SaveVouchers();
                //scope.Complete();
            }
            if (str != string.Empty)
            {
                Response.Redirect("CreditNoteView.aspx");
              //  lblMsg.Text = "Credit Note Updated Successfully !!";
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text += ex.Message;
        }
    }
    private void _SaveCreditNote_TDS(string status, string strCreditNoteChildId,bool ChkCheck, int rowIndex)
    {
        try
        {
            if (ChkCheck == true && status == "D")
            {
                if (strCreditNoteChildId != string.Empty && strCreditNoteChildId != "0")
                {
                    string strsql = "Delete from IVC_CREDITNOTE_TDS where CREDITNOTECHILDID=" + strCreditNoteChildId;
                    DU.executesql(strsql);
                }
            }
            else 
            {
                HiddenField hidServiceTaxRate = (HiddenField)tblCreditNoteMain.Rows[rowIndex].FindControl("hidServiceTaxRate" + rowIndex);
                HiddenField hidPECessRate = (HiddenField)tblCreditNoteMain.Rows[rowIndex].FindControl("hidPECessRate" + rowIndex);
                HiddenField hidHECessRate = (HiddenField)tblCreditNoteMain.Rows[rowIndex].FindControl("hidHECessRate" + rowIndex);
                TextBox txtTDSAmtCN = (TextBox)tblTdsCreditNote.Rows[rowIndex].FindControl("txtTDSAmtCN" + rowIndex);
                HiddenField hidServiceTaxAmtCN = (HiddenField)tblTdsCreditNote.Rows[rowIndex].FindControl("hidServiceTaxAmtCN" + rowIndex);
                HiddenField hidPECessAmtCN = (HiddenField)tblTdsCreditNote.Rows[rowIndex].FindControl("hidPECessAmtCN" + rowIndex);
                HiddenField hidHECessAmtCN = (HiddenField)tblTdsCreditNote.Rows[rowIndex].FindControl("hidHECessAmtCN" + rowIndex);

                HiddenField hidTDSAmtWithoutSTCN = (HiddenField)tblTdsCreditNote.Rows[rowIndex].FindControl("hidTDSAmtWithoutSTCN" + rowIndex);

                if (hidServiceTaxAmtCN.Value != string.Empty && Convert.ToDouble(hidServiceTaxAmtCN.Value) == 0)
                {
                    hidServiceTaxRate.Value = "0";
                    hidPECessRate.Value = "0";
                    hidHECessRate.Value = "0";
                    hidPECessAmtCN.Value = "0";
                    hidHECessAmtCN.Value = "0";
                    hidTDSAmtWithoutSTCN.Value = "0";
                }
                if (txtTDSAmtCN.Text == string.Empty)
                {
                    txtTDSAmtCN.Text = "0";
                }

                SqlParameter[] sparam ={
                                       new SqlParameter("@CREDITNOTECHILDID",strCreditNoteChildId),
                                       new SqlParameter("@CESS1RATE",hidPECessRate.Value),
                                       new SqlParameter("@CESS1AMT",hidPECessAmtCN.Value),
                                       new SqlParameter("@CESS2RATE",hidHECessRate.Value),
                                       new SqlParameter("@CESS2AMT",hidHECessAmtCN.Value),
                                       new SqlParameter("@SERVICERATE",hidServiceTaxRate.Value),
                                       new SqlParameter("@SERVICEAMT",hidServiceTaxAmtCN.Value),
                                       new SqlParameter("@TDS",txtTDSAmtCN.Text),
                                       new SqlParameter("@TDSTAXABLEAMT",hidTDSAmtWithoutSTCN.Value),
                                       new SqlParameter("@ABATEMENTAMT","0"),
                                       new SqlParameter("@SERVICECHARGEAMT","0")
                                   };
                DU.executeprocedure("USP_IVC_SaveCreditNoteTDSDetails", sparam);
            }
        }
        catch (Exception ex)
        { 
            lblMsg.Text += ex.Message;
            throw ex;
           
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Welcome.aspx");
    }

    protected void Add_OLDID()
    {
        OldIDCounter++;
        HtmlTableRow row = new HtmlTableRow();
        HtmlTableCell cell = new HtmlTableCell();
        HiddenField hidOldChildID = new HiddenField();
        hidOldChildID.ID = "hidOldChildID" + OldIDCounter.ToString();
        LstHidChildID.Add(hidOldChildID.ID);
        cell.Controls.Add(hidOldChildID);
        row.Cells.Add(cell);

        HtmlTableCell cell1 = new HtmlTableCell();
        HiddenField hidRefID = new HiddenField();
        hidRefID.ID = "hidRefID" + OldIDCounter.ToString();
        LstHidRefID.Add(hidRefID.ID);
        cell.Controls.Add(hidRefID);
        row.Cells.Add(cell1);
        tblOldChildID.Rows.Add(row);
        LstOldIdCounter.Add(OldIDCounter.ToString());
        ViewState["LstOldIdCounter"] = LstOldIdCounter;
        ViewState["LstHidChildID"] = LstHidChildID;
        ViewState["LstHidRefID"] = LstHidRefID;
    }

    protected void Override_OLDID()
    {
        LstOldIdCounter = (List<string>)ViewState["LstOldIdCounter"];
        LstHidChildID =(List<string>)ViewState["LstHidChildID"];
        LstHidRefID = (List<string>)ViewState["LstHidRefID"];
      
        if (LstOldIdCounter != null)
        {
            int intOLDIDCount = Convert.ToInt32(LstOldIdCounter.Count);

            for (int i = 0; i < intOLDIDCount; i++)
            {
                HtmlTableRow row = new HtmlTableRow();
                HtmlTableCell cell = new HtmlTableCell();
                HiddenField hidOldChildID = new HiddenField();
                hidOldChildID.ID = LstHidChildID[i].ToString();
                cell.Controls.Add(hidOldChildID);

                HtmlTableCell cell1 = new HtmlTableCell();
                HiddenField hidRefID = new HiddenField();
                hidRefID.ID = LstHidRefID[i].ToString();
                cell1.Controls.Add(hidRefID);
                row.Cells.Add(cell);
                row.Cells.Add(cell1);

                tblOldChildID.Rows.Add(row);
            }
        }
    }

}

    //protected void BindCreditnoteMain()
    //{
    //    if (hidVoudate.Value != string.Empty)
    //    {
    //        txtDate.Text = hidVoudate.Value.ToString();
    //    }

    //    /* Binding Credit Note Details From IVC_CREDITNOTE_MAIN table */

    //    string sql = "select * from IVC_CREDITNOTE_MAIN where creditnoteid =" + hidCreditNoteID.Value.ToString();
    //    DataTable dt = DU.getdata(sql);
    //    if (dt.Rows.Count > 0)
    //    {
    //        txtPreparedBy.Text = dt.Rows[0]["PREPAREDBY"].ToString();
    //        txtCheckedBy.Text = dt.Rows[0]["CHECKEDBY"].ToString();
    //        txtRemarks.Text = dt.Rows[0]["REMARKS"].ToString();
    //        string customer = dt.Rows[0]["CUSTOMERLEDGERID"].ToString();
    //        ddlCustomer.SelectedValue = customer;
    //        string Billformat = dt.Rows[0]["FORMATID"].ToString();
    //        ddlFormat.SelectedValue = Billformat;
    //        ddlFormat.Enabled = false;
    //        if (dt.Rows[0]["ISSALESRETURN"].ToString() == "False")
    //        {
    //            rbtCreditNoteType.SelectedValue = "0";
    //        }
    //        else
    //        {
    //            rbtCreditNoteType.SelectedValue = "1";
    //        }
    //    }

    //    /* Binding Credit Note Child Details IVC_CREDITNOTEID_CHILD table */

    //    string sql2 = "select * from IVC_CREDITNOTE_CHILD where creditnoteid =" + hidCreditNoteID.Value.ToString() ;
    //    DataTable dt1 = DU.getdata(sql2);
    //    if (dt1.Rows.Count > 0)
    //    {              
    //        if (dt1.Rows.Count > 1)
    //        {
    //            for (int i = 1; i < dt1.Rows.Count; i++)
    //            {
    //               // Response.Write("In Second row count=" + i);
    //              _AddMoreRow_MainTable();
    //            }
    //        }

    //        for (int i = 0; i < dt1.Rows.Count; i++)
    //        {
    //            DropDownList ddl = (DropDownList)tblCreditNoteMain.FindControl("ddlInvoiceParticular" + (i + 1));
    //            DropDownList ddlServices = (DropDownList)tblCreditNoteMain.FindControl("ddlServices" + (i + 1));
    //            TextBox txtOriginalAmt = (TextBox)tblCreditNoteMain.FindControl("txtOriginalAmt" + (i + 1));
    //            TextBox txtPendingAmt = (TextBox)tblCreditNoteMain.FindControl("txtPendingAmt" + (i + 1));
    //            TextBox txtamount = (TextBox)tblCreditNoteMain.FindControl("txtTotalAmount" + (i + 1));
    //            TextBox txtAddDescription = (TextBox)tblCreditNoteMain.FindControl("txtAddDescription" + (i + 1));
    //            HiddenField hidTotalAmout = (HiddenField)tblCreditNoteMain.FindControl("hidTotalAmout" + (i + 1));
    //            HiddenField hidServiceTaxability = (HiddenField)tblCreditNoteMain.FindControl("hidServiceTaxability" + (i + 1));

    //            _GetParticular_MainTable(ddl);

    //            string Service = dt1.Rows[i]["SERVICEID"].ToString();
    //            ddlServices.SelectedValue = Service;
    //            string particular = dt1.Rows[i]["Referenceid"].ToString();
    //            ////Response.Write("ReferenceID=" + particular);
    //            //ddl.SelectedValue = particular;
    //            string strsql = "select parentref,reference from acc_refdetails where refserial=" + particular;
    //            DataTable dtparticulrid = DU.getdata(strsql);
    //            string ddstr = dtparticulrid.Rows[0]["parentref"].ToString();
    //            ddl.SelectedValue = ddstr;
    //            DataTable DTService = _ReturnPendingService_Details();
    //            DataView DVService = DTService.DefaultView;
    //            //DVService.RowFilter = "ReferenceSerial='" + particular + "'";
    //            DataTable DTTempService = DVService.ToTable();

    //            if (DTTempService.Rows.Count > 0)
    //            {
    //                ddlServices.DataSource = DTTempService;
    //                ddlServices.DataTextField = "ServiceName";
    //                ddlServices.DataValueField = "ServiceId";
    //                ddlServices.DataBind();
    //                ddlServices.Items.Insert(0, new ListItem("", "0"));
    //            }
    //            else
    //            {
    //                ddlServices.Items.Clear();
    //                ddlServices.Items.Insert(0, new ListItem("", "0"));
    //            }
    //            txtamount.Text = dt1.Rows[i]["AMOUNT"].ToString();

    //            DataTable DTParticular = _ReturnParticular();
    //            DataView DVParticular = DTParticular.DefaultView;
    //            DVParticular.RowFilter = "ReferenceId='" + ddl.SelectedValue + "'";
    //            DataTable DTTempParticular = DVParticular.ToTable();

    //            //string[] strOriginal = DTTempParticular.Rows[i]["OriginalAmount1"].ToString().Split(' ');
    //            //txtOriginalAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(strOriginal[0])) + " " + strOriginal[1];

    //            //string[] strPending = DTTempParticular.Rows[0]["PendingAmount1"].ToString().Split(' ');
    //            //txtPendingAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(strPending[0])) + " " + strPending[1];

    //            txtAddDescription.Text = dt1.Rows[i]["adddesc"].ToString();

    //            //DVService = DTService.DefaultView;
    //            //DVService.RowFilter = "ReferenceSerial='" + particular + "' and ServiceId='" + Service + "'";

    //            txtOriginalAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["Amount"].ToString()));
    //            txtPendingAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["PendingAmount"].ToString()));
    //            hidTotalAmout.Value = string.Format("{0:0.00}", Convert.ToDouble(DTTempService.Rows[0]["PendingAmount"].ToString()));
    //            hidServiceTaxability.Value = _GetRembursmentService(ddl.SelectedValue);
    //            int rowIndex = Convert.ToInt32(ddlServices.ID.ToString().Substring(11));

    //            if (dt.Rows[0]["ISSALESRETURN"].ToString() == "False")
    //            {

    //                _AddRow_tblCreditNote(i + 1);
    //                _BindDetails_tblTDSCreditNote(i + 1);
    //                DropDownList ddlInvoiceParticular = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlInvoiceParticular" + rowIndex);
    //                //TextBox txtTotalAmount = (TextBox)tblCreditNoteMain.Rows[rowIndex].FindControl("txtTotalAmount" + rowIndex);
    //                //DropDownList ddlServices = (DropDownList)tblCreditNoteMain.Rows[rowIndex].FindControl("ddlServices" + rowIndex);

    //                TextBox txtParticularCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtParticularCN" + (i + 1));
    //                TextBox txtServiceCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtServiceCN" + (i + 1));
    //                TextBox txtTDSAmtCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtTDSAmtCN" + (i + 1));
    //                TextBox txtDiscountCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtDiscountCN" + (i + 1));
    //                TextBox txtWriteOffCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtWriteOffCN" + (i + 1));
    //                TextBox txtTotalAmtCN = (TextBox)tblTdsCreditNote.Rows[(i + 1)].FindControl("txtTotalAmtCN" + (i + 1));
    //                txtTotalAmtCN.Attributes.Add("textalign", "right");
    //                txtTotalAmount.Text = dt1.Rows[i]["AMOUNT"].ToString();
    //                txtWriteOffCN.Text = dt1.Rows[i]["WRITEOFFAMT"].ToString();
    //                txtDiscountCN.Text = dt1.Rows[i]["DISCOUNTAMT"].ToString();
    //                txtTDSAmtCN.Text = dt1.Rows[i]["TDSAMOUNT"].ToString();
    //                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "CalculateTotalCreditNoteAmt();", true);
    //                panelCreditNote.Visible = true;
    //                panelSalesReturn.Visible = false;
    //            }
    //            else if (dt.Rows[0]["ISSALESRETURN"].ToString() == "True")
    //            {
    //                _AddRow_tblTDSSaleReturn(i + 1);

    //                _BindDetails_tblTDSSaleReturn(i + 1);

    //                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "CalculateTotalSaleReturnAmt();", true);
    //                panelCreditNote.Visible = false;
    //                panelSalesReturn.Visible = true;
    //            }
    //        }
    //        string strsqlqury = "select * from ACC_VOUCHERS where tranid=" + hidTranID.Value.ToString();
    //        DataTable dtVouchers = DU.getdata(strsqlqury);
    //        if (dtVouchers.Rows.Count > 0)
    //        {
    //            txtNarration.Text = dtVouchers.Rows[0]["NARRATION"].ToString();
    //            txtRefNo.Text = dtVouchers.Rows[0]["REFNO"].ToString();
    //            txtCreditNoteNo.Text=dtVouchers.Rows[0]["VOUNO"].ToString();
    //        }
    //    }
    //}